以下是我创建的测试用例。为什么每个进程都打印1到5的数字,并且这些数字是不分为进程的数字?
代码:
#!/usr/bin/python
from subprocess import *
from Queue import Queue
from Queue import Empty
import multiprocessing
from multiprocessing import Process
def main():
r = Runner()
r.run()
class Runner(object):
processes = []
def run(self):
q = Queue()
for t in range(1,6):
q.put(t)
for pi in range(1,4):
p = Process(target=self.runFromQueue, args=(q,))
p.start()
self.processes.append(p)
for p in self.processes:
p.join()
print "Finished!"
def runFromQueue(self, q):
try:
while True:
number = q.get_nowait()
print str(number)
q.task_done()
except Empty:
pass
if __name__ == "__main__":
main()
输出继电器:
$ ./test_threads.py
1
2
3
4
5
1
1
2
3
2
4
3
5
4
5
Finished!
预期的输出:
$ ./test_threads.py
1
2
3
4
5
Finished!
答案 0 :(得分:8)
Queue包不是进程感知的,它只适用于线程。您的示例中会出现以下情况:
您必须使用多处理提供的Queue类。