python 實現(xiàn)兩個線程交替執(zhí)行
我就廢話不多說,直接看代碼吧!
import threadingimport timedef a(): while True: lockb.acquire() print(’a’) locka.release() time.sleep(0.5)def b(): while True: locka.acquire() print(’b’) lockb.release() time.sleep(0.5)if __name__ == '__main__': locka = threading.Lock() lockb = threading.Lock() ta = threading.Thread(None, a) tb = threading.Thread(None, b) locka.acquire() #保證a先執(zhí)行 ta.start() tb.start()
獲取對方的鎖,運行完后釋放自己的鎖
補充知識:線程同步——兩個線程輪流執(zhí)行python實現(xiàn)
看代碼!
import threadingimport timelockA=threading.Lock()lockB=threading.Lock()def printA(n): if n<0: return lockA.acquire() print('+++') lockB.release() time.sleep(0.1) printA(n-1)def printB(n): if n<0: return lockB.acquire() print('***') lockA.release() time.sleep(0.2) printB(n-1) lockB.acquire()t1=threading.Thread(target=printA,args=(10,))t2=threading.Thread(target=printB,args=(10,))t1.start()t2.start()t1.join()t2.join()
找實習,又要回憶起操作系統(tǒng)的東西了。
思想:創(chuàng)建兩個鎖lockA和lockB。每次執(zhí)行完后,鎖掉自己的鎖,并釋放對方的鎖。
初始時,若A先運行,則釋放A的鎖,鎖住B的鎖。
以上這篇python 實現(xiàn)兩個線程交替執(zhí)行就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持好吧啦網。
相關文章:
1. ASP實現(xiàn)加法驗證碼2. ASP 信息提示函數(shù)并作返回或者轉向3. 將properties文件的配置設置為整個Web應用的全局變量實現(xiàn)方法4. asp(vbs)Rs.Open和Conn.Execute的詳解和區(qū)別及&H0001的說明5. CSS hack用法案例詳解6. ASP.NET MVC遍歷驗證ModelState的錯誤信息7. asp中response.write("中文")或者js中文亂碼問題8. PHP設計模式中工廠模式深入詳解9. jsp網頁實現(xiàn)貪吃蛇小游戲10. 用css截取字符的幾種方法詳解(css排版隱藏溢出文本)
