更新时间:2023-02-01 21:22:31
让我们弄清楚:
worker(q)
在上述方案中仅被调用一次.在第一次调用时,该函数将暂停等待阻塞操作q.get()
的结果.它从queue
获取实例MyFancyClass('Fancy Dan')
,调用其do_something
方法并完成操作.MyFancyClass('Frankie')
将被放入队列中,但不会进入Process,因为该进程的目标功能已完成.None
值.worker(q)
will be called just once in the above scheme. At that first call the function will suspend waiting the result from blocking operation q.get()
. It gets the instance MyFancyClass('Fancy Dan')
from the queue
, invokes its do_something
method and get finished.MyFancyClass('Frankie')
will be put into the queue but won't go to the Process cause the process' target function is done.None
value.import multiprocessing
class MyFancyClass:
def __init__(self, name):
self.name = name
def do_something(self):
proc_name = multiprocessing.current_process().name
print('Doing something fancy in {} for {}!'.format(proc_name, self.name))
def worker(q):
while True:
obj = q.get()
if obj is None:
break
obj.do_something()
if __name__ == '__main__':
queue = multiprocessing.Queue()
p = multiprocessing.Process(target=worker, args=(queue,))
p.start()
queue.put(MyFancyClass('Fancy Dan'))
queue.put(MyFancyClass('Frankie'))
# print(queue.qsize())
queue.put(None)
# Wait for the worker to finish
queue.close()
queue.join_thread()
p.join()
输出:
Doing something fancy in Process-1 for Fancy Dan!
Doing something fancy in Process-1 for Frankie!