# 线程锁套线程锁,即为递归锁
import threading def run1(): print("grab the first part data") lock.acquire() global num num += 1 lock.release() return num def run2(): print("grab the second part data") lock.acquire() global num2 num2 += 1 lock.release() return num2 def run3(): lock.acquire() res= run1() print("----between run1 and run2----") res2 = run2() lock.release() print(res, res2) num, num2 = 0, 0 # 递归锁,使用RLock(), 使用Lock()会进入无限死循环 lock = threading.RLock() for i in range(1): t = threading.Thread(target=run3) t.start() while threading.active_count() != 1: print("当前活跃的线程数:", threading.active_count()) else: print("--all threads done---") print("打印num和num2:", num, num2)
信号量:控制线程一次运行的个数
import threading semaphore = threading.BoundedSemaphore(5) def run(n): semaphore.acquire() time.sleep(1) print("run the thread:%s " % n) semaphore.release() if __name__ == '__main__': for i in range(22): t = threading.Thread(target=run, args=(i,)) t.start()
Event事件
import threading event = threading.Event() # event.set() 设置标识 event.clear() 清除标志位 event.is_set() 判断是否存在标志位 event.wait() 等待的时长 def lighter(): count = 0 event.set() # 刚开始的标识位先设置绿灯 while True: if 5 < count < 10: # 改成红灯 event.clear() # 把标志位清了 print("