进程锁:
from multiprocessing import Process, Lock def f(l, i): l.acquire() print('hello world', i) l.release() if __name__ == '__main__': lock = Lock() for num in range(10): Process(target=f, args=(lock, num)).start()
进程池:
from multiprocessing import Process, Pool import time def Foo(i): time.sleep(2) return i+100 def Bar(arg): print('----->exec done:',arg) pool = Pool(5) #允许进程池里同时放入5个进程 for i in range(10): pool.apply_async(func=Foo,args=(i,),callback=Bar) #并行执行,callback回调执行者为父进程 #pool.apply(func=Foo, args=(i,)) #串行执行 print('end') pool.close() pool.join() #进程池中进程执行完毕后再关闭,如果注释,那么程序直接关闭。