# print same numbers in arbitrary order for i in pool.imap_unordered(f, range(10)): print(i)
# evaluate "f(20)" asynchronously res = pool.apply_async(f, (20,)) # runs in *only* one process print(res.get(timeout=1)) # prints "400"
# evaluate "os.getpid()" asynchronously res = pool.apply_async(os.getpid, ()) # runs in *only* one process print(res.get(timeout=1)) # prints the PID of that process
# launching multiple evaluations asynchronously *may* use more processes multiple_results = [pool.apply_async(os.getpid, ()) for i in range(4)] print([res.get(timeout=1) for res in multiple_results])
# make a single worker sleep for 10 secs res = pool.apply_async(time.sleep, (10,)) try: print(res.get(timeout=1)) except TimeoutError: print("We lacked patience and got a multiprocessing.TimeoutError")
print("For the moment, the pool remains available for more work")
# exiting the 'with'-block has stopped the pool print("Now the pool is closed and no longer available")
from multiprocessing import Process import os import time
defnow(): return str(time.time())
deff(): print('Run child process ' + str(os.getpid()) + ' at ' + str(now())) time.sleep(3) print('Stop child process ' + str(os.getpid()) + ' at ' + str(now()))
if __name__ == '__main__': print ('Parent process ' + str(os.getpid())) p1 = Process(target=f, args=()) print('Process start at '+ str(now())) p1.start() p1.join() print('Process end at '+ str(now()))
# 输出 # 如果没p1.join(),则主进程会在子进程结束之前执行Process end 打印 Parent process 2 Process start at 1581322409.9711816 Run child process 3 at 1581322409.975377 Stop child process 3 at 1581322412.9764113 Process end at 1581322412.9770644
deff(): print("work start at {}".format(time.time())); time.sleep(3) print("work end at {}".format(time.time()));
if __name__ == "__main__": p = multiprocessing.Process(target = f, args = ()) p.daemon = True# 设置是否为守护进程 p.start() print("Process end")
# 输出 # 因为守护进程随主进程的结束而结束,所以如果加了p.daemon = True,则只会输出 Process end Process end work start at 1581323384.468953# 如果不加p.daemon = True,则输出该行 work end at 1581323387.4720087# 如果不加p.daemon = True,则输出该行
信号量
信号量(Semaphore)
概念 该类实现信号量对象。信号量对象管理一个原子性的计数器,代表 release() 方法的调用次数减去 acquire() 的调用次数再加上一个初始值。如果需要, acquire() 方法将会阻塞直到可以返回而不会使得计数器变成负数。在没有显式给出 value 的值时,默认为1。
if __name__ == '__main__': e = Event() traffic = Process(target=traffic_light, args=(e,)) traffic.daemon = True traffic.start() for i in range(30): if i % 6: time.sleep(random.random()) car_obj = Process(target=car, args=(i, e)) car_obj.start()