我无法弄清楚以下python多处理代码有什么问题。它不会终止。任何建议都将受到高度赞赏。
from multiprocessing import Process, Queue, Lock
def hello(num, myqueue):
while True:
item = myqueue.get()
print 'Thread ', num, 'got', item
return
def put_on_queue(myqueue):
for i in range(10):
myqueue.put(i)
return
if __name__ == '__main__':
processes = []
myqueue = Queue()
for i in range(4):
proc = Process(target = hello, args = (i, myqueue))
proc.start()
processes.append(proc)
put_on_queue(myqueue)
for proc in processes:
proc.join()
--------------编辑-----------------
好的,基于我收到的评论和一些在线帮助,我修改了我的代码,如下所示。仍然没有运气: - (
def hello(num, myqueue):
while not exit_flag:
item = myqueue.get(False,5)
print 'Thread ', num, 'got', item
return
def put_on_queue(myqueue):
global exit_flag
for i in range(10):
myqueue.put(i)
while not myqueue.empty():
pass
exit_flag = 1
return
if __name__ == '__main__':
mylock = Lock()
processes = []
myqueue = Queue()
exit_flag = 0
for i in range(4):
proc = Process(target = hello, args = (i, myqueue))
#proc.daemon = True
proc.start()
processes.append(proc)
put_on_queue(myqueue)
for proc in processes:
proc.join()
答案 0 :(得分:1)
hello
函数中存在无限循环。
你必须将一个感知作为最后一个值放入队列,检查它并突破循环。