# 信号量 也是同步锁,可用来控制线程的并发数 import threading, time class MyThread(threading.Thread): def run(self): if semaphore.acquire(): # 同时运行五个线程,acquire()放一个进程进去计数器-1 print(self.name) # 计数器为0时阻塞线程至同步锁定状态,等待release() time.sleep(3) semaphore.release() # release()运行一次计数器+1 if __name__ == ‘__main__‘: semaphore = threading.Semaphore(5) # 设定一个信号量同步锁,每一时刻可并行5个线程 thrs = [] for i in range(100): # 创建100个线程 thrs.append(MyThread()) for t in thrs: # 运行100个线程 t.start()
原文地址:https://www.cnblogs.com/dangrui0725/p/9498542.html
时间: 2024-11-07 23:21:14