这里的job.get()是什么含义?

代码来源
https://medium.com/geekculture/python-multiprocessing-with-ou...

import multiprocessing as mp

def worker_function(item):
    """
    do some work, write results to output
    """
    res = f'item: {item} - result: {item ** 2}'
    print(res)
    with open('output_no_queue.txt', 'a') as f:
        f.write(str(res) + '\n')


if __name__ == '__main__':
    pool = mp.Pool(16)
    jobs = []
    for item in range(10000):
        job = pool.apply_async(worker_function, (item, ))
        jobs.append(job)

    for job in jobs:
        job.get()

    pool.close()
    pool.join()

这里的job.get()是表达什么呢?jobs是个list,每个job也不是queue,list的元素没有get方法,如何理解呢?

阅读 3k
4 个回答

企业微信截图_16860211759044.png
看看这个图就是知道了,用来解决并发的

job 是 apply_async 的返回值,是 AsyncResult 类的对象。这个类的对象的 get:

Return the result when it arrives. If timeout is not None and the result does not arrive within timeout seconds then multiprocessing.TimeoutError is raised. If the remote call raised an exception then that exception will be reraised by get().

直接拿官网定义截图给你:
image.png

apply_async(func[, args[, kwds[, callback[, error_callback]]]])

A variant of the apply() method which returns a AsyncResult object.

If callback is specified then it should be a callable which accepts a single argument. When the result becomes ready callback is applied to it, that is unless the call failed, in which case the error_callback is applied instead.

If error_callback is specified then it should be a callable which accepts a single argument. If the target function fails, then the error_callback is called with the exception instance.

Callbacks should complete immediately since otherwise the thread which handles the results will get blocked.

然后再看 AsyncResult 的定义:

image.png

他有一个 get 方法,也就是你问的问题所在了。返回的是你的执行结果。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进