我正在使用Python的多处理模块。我从这个程序开始:
import multiprocessing
def worker(num):
"""thread worker function"""
print 'Worker:', num
return
if __name__ == '__main__':
for i in range(5):
p = multiprocessing.Process(target=worker, args=(i,))
p.start()
令我惊讶的是,结果总是这样:
Worker: 0
Worker: 1
Worker: 2
Worker: 3
Worker: 4
我希望工人们不时以不同的顺序输出,但无论我运行多少次,都不会发生这种情况。我在哪里误会了?
答案 0 :(得分:1)
您的代码很好,速度非常快。试试这个添加一些抖动:
import multiprocessing
from random import randint
from time import sleep
def worker(num):
"""thread worker function"""
sleep(randint(0, 5))
print 'Worker:', num
return
if __name__ == '__main__':
for i in range(5):
p = multiprocessing.Process(target=worker, args=(i,))
p.start()