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。在评论中,任何稍微不同的时间都可以(如果我能控制的话会更好)。但是,我不希望工人在他们做的每一份工作之前都睡觉。我只是希望3名工人在不同的时间开始,但之后从不在工作之间睡觉。所以,我不确定在工作函数中使用time.sleep是否有效。
答案 0 :(得分:2)
池可以在子进程中运行初始化程序。用它来等待。
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()