import multiprocessing as mp
from datetime import datetime
def worker(a):
print(str(a)+": "+str(datetime.now()))
time.sleep(1)
pool=mp.Pool(3)
if __name__ == '__main__':
pool.map(worker,range(10))
输出为:
0: 2017-04-18 23:37:31.399574
1: 2017-04-18 23:37:31.400422
2: 2017-04-18 23:37:31.400571
3: 2017-04-18 23:37:32.401644
4: 2017-04-18 23:37:32.401765
5: 2017-04-18 23:37:32.401904
6: 2017-04-18 23:37:33.403168
7: 2017-04-18 23:37:33.403250
8: 2017-04-18 23:37:33.403370
9: 2017-04-18 23:37:34.405025
3名工人同时开始。
我真的很想知道,可以通过(稍有(不同的时间启动3名工人?
预先感谢!
ps。就像评论中一样,任何稍微不同的时间都会好起来(如果我可以控制的话,会更好(。但是,我不希望工人在每份工作之前都睡觉。我只希望这三名工人在不同的时间开始,但后来从未在工作之间睡觉。因此,我不确定要花费时间。
池可以在子过程中运行初始化器。用它等待。
import multiprocessing as mp
from datetime import datetime
import time
import random
import os
def sleepy():
nap = random.randint(1,10)
print(os.getpid(), 'sleeps', nap)
time.sleep(nap)
def worker(a):
print(os.getpid(), str(a)+": "+str(datetime.now()))
time.sleep(1)
pool=mp.Pool(3, initializer=sleepy)
if __name__ == '__main__':
pool.map(worker,range(10))
您可以通过与时代的队列创建队列来控制睡眠时间。每个初始化器读取一个值
import multiprocessing as mp
from datetime import datetime
import time
import random
import os
import threading
def sleepy(time_q):
timeout = time_q.get()
print(os.getpid(), 'sleeps', timeout, datetime.now())
time.sleep(timeout)
def worker(a):
print(os.getpid(), 'worker', str(a)+": "+str(datetime.now()))
time.sleep(1)
if __name__ == '__main__':
pool_size = 3
time_q = mp.Queue()
for sleep_time in range(1, pool_size+1):
time_q.put(sleep_time)
pool=mp.Pool(pool_size, initializer=sleepy, initargs=(time_q,))
pool.map(worker,range(10))
time_q.close()
time_q.join()