信号量:限制同一时间的多个进程运行
使用:
from threading import Semaphore
sm=Semaphore(5)
from threading import Thread,Semaphore import time,random sm=Semaphore(5) def task(name): sm.acquire() #或者with sm print('%s 正在上厕所' %name) time.sleep(random.randint(1,3)) sm.release() #保证是5个 if __name__ == '__main__': for i in range(10): t=Thread(target=task,args=('路人%s' %i,)) t.start() 结果: 路人0 正在上厕所 路人1 正在上厕所 路人2 正在上厕所 路人3 正在上厕所 路人4 正在上厕所 路人5 正在上厕所 路人6 正在上厕所 路人7 正在上厕所 路人8 正在上厕所 路人9 正在上厕所