Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pool.apply_async function in Python prints number in order

Tags:

python

This question is about Pool apply_async function. Shouldn't this function call other function 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 in order? Shouldn't the output sometimes be out of order?

like image 265
john smith Avatar asked Aug 26 '26 09:08

john smith


1 Answers

Your function is too fast, and has a constant execution time... so things just fall in order.

Try to add

time.sleep(random.random())

into your foo_pool to see some asynchronicity.

like image 133
Amadan Avatar answered Aug 29 '26 00:08

Amadan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!