Python: Yield in multiprocessing Pool

别说谁变了你拦得住时间么 提交于 2019-12-03 16:15:08

When a function containing a yield statement is called, it doesn't actually run the code but returns a generator instead:

>>> p = parallel(1, 2, 3)
>>> p
<generator object parallel at 0x7fde9c1daf00>

Then, when the next value is required, the code will run until a value is yielded:

>>> next(p)
([10000], 6)
>>> next(p)
(6, [10000])

In your case, results contains 10 generators that have been created asynchronously, but they've never been actually run.

If you want to use a generator, you could change your code a bit to target a function that creates a list from the generator:

def parallel2(x, y, z):
    return list(parallel(x, y, z))

def collect_results(lst):
   results.extend(lst)

def apply_async_with_callback():
    pool = mp.Pool()
    for _ in range(10):
        pool.apply_async(parallel2, args=(2, 5, 7),
                         callback=collect_results)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!