python进程池和进程锁
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')