SoFunction
Updated on 2024-11-12

Difference between apply method and apply_async method in python process pool Pool

Before you can grasp the difference between the apply method and apply_async, you need to understand the difference between blocking and non-blocking

blockage

Obstruction is like crossing a log bridge; if the person in front doesn't go, the person behind can't go earlier, and only if the person in front crosses the log bridge, the person behind can continue to go forward.

non-blocking

The logic of non-blocking is the opposite of blocking, which means that if the person in front of you doesn't go, you stay on the sidelines and let the person behind you go first, the

apply is the blocking mode above, and apply_async is the non-blocking mode.

an actual example

import multiprocessing
def fun(name):
    print(name)


if __name__=="__main__":
    pool = (3)
    for i in range(1,6):
        st = "start {}".format(i)
        (func=fun,args=(st,))

    print("this is flag!")
    ()
    ()

As you can see by the following screenshot of the execution result, theprint("this is flag!")Execute tasks in the thread pool after they have finished executing

2. apply_async example

import multiprocessing
def fun(name):
    print(name)


if __name__=="__main__":
    pool = (3)
    for i in range(1,6):
        st = "start {}".format(i)
        pool.apply_async(func=fun,args=(st,))

    print("this is flag!")
    ()
    ()

in apply_asyncprint("this is flag!")The code is executed before the process pool

summarize

The above is a personal experience, I hope it can give you a reference, and I hope you can support me more.