BoundedSemaphore对象:
from threading import Thread, BoundedSemaphore
from time import time,sleep
def execute(i):
start=time()
with sem:
end=time()
print("Thread: {0} waiting time:{1}".format(i,end-start))
sleep(2)
sem=BoundedSemaphore(3) #控制同一时刻最多允许三个线程访问资源
for i in range(12):
Thread(target=execute,args=(i,)).start()
Pool对象:
from multiprocessing import Pool
def isPrime(n):
if n<2:
return 0
if n==2:
return 1
for i in range(2,int(n*0.5)+1):
if n%i==0:
return 0
return 1
if __name__=='__main__':
with Pool(5) as p: #进程池对象并行处理
print(sum(p.map(isPrime,range(100))))