Python-threading多线程进阶
# 线程锁套线程锁,即为递归锁
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" % 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("\033[41;1mred light is on....\033[0m") elif count > 10: event.set() # 变绿灯 count = 0 else: print("\033[42;1mgreen light is on....\033[0m") time.sleep(1) count += 1 def car(name): while True: if event.is_set(): # 代表绿灯 print("[%s] running..." % name) time.sleep(1) else: print("[%s] sees red light , waiting...." % name) event.wait() print("\033[34;1m[%s] green light is on, start going...\033[0m" % name) light = threading.Thread(target=lighter, ) light.start() car1 = threading.Thread(target=car, args=("Tesla",)) car1.start()