3
以下是我創建的測試用例。爲什麼每個流程都打印1到5的數字,並且是沒有在流程中劃分的數字?爲什麼這個python隊列代碼處理項目多次?
代碼:
#!/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!
噢,這就是它。謝謝! – 2010-03-08 12:58:14