1.进程锁:
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()
2.进程池:
from multiprocessing import Pool
import time
def Foo(i):
time.sleep(2)
print(i+100)
#允许进程池里同时放入5个进程
pool = Pool(5)
for i in range(10):
#并行执行
pool.apply_async(func=Foo,args=(i,))
pool.close()
pool.join() #进程池中进程执行完毕后再关闭,如果注释,那么程序直接关闭。
print(‘end’)
3.进程池与进程锁:
from multiprocessing import Pool, Manager
import time
def Foo(i, l):
l.acquire()
time.sleep(2)
print(i+100)
l.release()
lock = Manager().Lock()
#允许进程池里同时放入5个进程
pool = Pool(5)
for i in range(10):
#并行执行
pool.apply_async(func=Foo,args=(i, lock, ))
pool.close()
pool.join() #进程池中进程执行完毕后再关闭,如果注释,那么程序直接关闭。
print(‘end’)