Python的BoundedSemaphore对象和Pool对象实例

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))))

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_43873198/article/details/107559388