python 實(shí)現(xiàn)兩個(gè)線程交替執(zhí)行
我就廢話不多說(shuō),直接看代碼吧!
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()
獲取對(duì)方的鎖,運(yùn)行完后釋放自己的鎖
補(bǔ)充知識(shí):線程同步——兩個(gè)線程輪流執(zhí)行python實(shí)現(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()
找實(shí)習(xí),又要回憶起操作系統(tǒng)的東西了。
思想:創(chuàng)建兩個(gè)鎖lockA和lockB。每次執(zhí)行完后,鎖掉自己的鎖,并釋放對(duì)方的鎖。
初始時(shí),若A先運(yùn)行,則釋放A的鎖,鎖住B的鎖。
以上這篇python 實(shí)現(xiàn)兩個(gè)線程交替執(zhí)行就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. CSS清除浮動(dòng)方法匯總2. XML入門(mén)的常見(jiàn)問(wèn)題(三)3. 不要在HTML中濫用div4. React優(yōu)雅的封裝SvgIcon組件示例5. CSS百分比padding制作圖片自適應(yīng)布局6. js開(kāi)發(fā)中的頁(yè)面、屏幕、瀏覽器的位置原理(高度寬度)說(shuō)明講解(附圖)7. XML 非法字符(轉(zhuǎn)義字符)8. HTML5實(shí)戰(zhàn)與剖析之觸摸事件(touchstart、touchmove和touchend)9. 深入了解React中的合成事件10. TypeScript實(shí)現(xiàn)十大排序算法之歸并排序示例詳解
