Python – The Pool.apply_async function in Python prints numbers sequentially

The Pool.apply_async function in Python prints numbers sequentially… here is a solution to the problem.

The Pool.apply_async function in Python prints numbers sequentially

This question is about the Pool apply_async function.
Shouldn’t this function call other functions asynchronously?

Code:

import multiprocessing as mp

def foo_pool(x): return x

result_list = []

def log_result(result): result_list.append(result)

def apply_async_with_callback():
    pool = mp. Pool()
    for i in range(10):
        pool.apply_async(foo_pool, args = (i, ), callback = log_result)
    pool.close()
    pool.join()
    print(result_list)

if __name__ == '__main__':
    apply_async_with_callback()

After running this code for a while, I keep getting this print:

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Why is it orderly? Shouldn’t the output be out of order sometimes?

Solution

Your function is too fast, and the execution time is constant… So everything is in order.

Try adding

time.sleep(random.random())

Go into your foo_pool to see some asynchronicity.

Related Problems and Solutions