小編給大家分享一下python中怎么實(shí)現(xiàn)threading線程同步,希望大家閱讀完這篇文章之后都有所收獲,下面讓我們一起去探討吧!
創(chuàng)新互聯(lián)堅(jiān)持“要么做到,要么別承諾”的工作理念,服務(wù)領(lǐng)域包括:成都網(wǎng)站設(shè)計(jì)、成都做網(wǎng)站、企業(yè)官網(wǎng)、英文網(wǎng)站、手機(jī)端網(wǎng)站、網(wǎng)站推廣等服務(wù),滿足客戶于互聯(lián)網(wǎng)時(shí)代的興業(yè)網(wǎng)站設(shè)計(jì)、移動(dòng)媒體設(shè)計(jì)的需求,幫助企業(yè)找到有效的互聯(lián)網(wǎng)解決方案。努力成為您成熟可靠的網(wǎng)絡(luò)建設(shè)合作伙伴!
說(shuō)明
1、threading模塊具有實(shí)現(xiàn)鎖定的內(nèi)置功能,允許同步線程。為了防止數(shù)據(jù)損壞或丟失,需要鎖定來(lái)控制共享資源的訪問(wèn)。
2、可以調(diào)用Lock()方法來(lái)應(yīng)用鎖,它新的鎖對(duì)象。然后,可以調(diào)用鎖對(duì)象的獲取(阻塞)方法來(lái)強(qiáng)制線程同步運(yùn)行。
實(shí)例
#Python 多線程示例來(lái)演示鎖定。 #1. 使用 threading.Thread 類定義子類。 #2. 實(shí)例化子類并觸發(fā)線程。 #3. 在線程的 run 方法中實(shí)現(xiàn)鎖。 import threading import datetime exitFlag = 0 class myThread (threading.Thread): def __init__(self, name, counter): threading.Thread.__init__(self) self.threadID = counter self.name = name self.counter = counter def run(self): print("\nStarting " + self.name) # 獲取鎖同步線程 threadLock.acquire() print_date(self.name, self.counter) # 為下一個(gè)線程釋放鎖 threadLock.release() print("Exiting " + self.name) def print_date(threadName, counter): datefields = [] today = datetime.date.today() datefields.append(today) print("{}[{}]: {}".format( threadName, counter, datefields[0] )) threadLock = threading.Lock() threads = [] # 創(chuàng)建新線程 thread1 = myThread("Thread", 1) thread2 = myThread("Thread", 2) # 啟動(dòng)新線程 thread1.start() thread2.start() # 添加線程到線程列表 threads.append(thread1) threads.append(thread2) # 等待所有線程完成 for thread in threads: thread.join() print("\nExiting the Program!!!")
看完了這篇文章,相信你對(duì)“python中怎么實(shí)現(xiàn)threading線程同步”有了一定的了解,如果想了解更多相關(guān)知識(shí),歡迎關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道,感謝各位的閱讀!