python之迭代锁与信号量
生活随笔
收集整理的這篇文章主要介紹了
python之迭代锁与信号量
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
如果現在需要在多處加鎖大于等于2的時候 因為計算機比較笨,當他鎖上一把鎖的時候又所理一把鎖,等他來開鎖的時候他不知道用哪把鑰匙來開鎖,
所以這個時候我們需要把把平常的鎖變為迭代鎖
eg:
import threading import timelocal = threading.RLock() # 迭代加鎖首先生成實例 def run(name):global numlocal.acquire() # 上鎖num += 1run2(num)local.release() # 解鎖print(threading.active_count())def run2(num):local.acquire()num += 1run3(num)local.release()def run3(num):local.acquire()num+=1local.release()num = 0 py_res = [] for i in range(50):t = threading.Thread(target=run,args=('t%s'%i,))py_res.append(t)t.start()for i in py_res:i.join()print("num : %s"% num)型號量可以控制同線程的個數,和鎖的用法一樣
import threading import time senm = threading.BoundedSemaphore(5) def run(num):senm.acquire() # 上鎖time.sleep(2)print('run the thread %s' % num)senm.release() # 解鎖for i in range(50):t = threading.Thread(target=run, args=('%s' % i,))t.start()print(threading.active_count())while threading.active_count() != 1:pass else:print('is done')?信號量:event
標志位 :set,設置標志位 clear 設置標志位,wait 等帶標志位,is_set 判斷是否設置了標志
下面是一個紅綠燈的程序,實現紅燈停綠燈行
import threading import time event = threading.Event() # red is have flag or nodef light():count = 0while True:if count > 5 and count <= 10:print('red')event.set()elif count > 10:print('green')event.clear()count = 0else:print('in the else')time.sleep(1)count += 1 def car(name):while True:if event.is_set():print('the %s is runing...' % name)time.sleep(1)else:print('%s is wait...' % name)event.wait()t1 = threading.Thread(target=light) t1.start() t2 = threading.Thread(target=car, args=('tesla', )) t2.start()?
轉載于:https://www.cnblogs.com/BookMiki/p/10202613.html
總結
以上是生活随笔為你收集整理的python之迭代锁与信号量的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 2018总结及2019计划
- 下一篇: Visual studio中编译和使用l