溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

python中怎么實(shí)現(xiàn)threading線程同步

發(fā)布時(shí)間:2021-07-29 13:36:12 來源:億速云 閱讀:233 作者:小新 欄目:編程語言

小編給大家分享一下python中怎么實(shí)現(xiàn)threading線程同步,希望大家閱讀完這篇文章之后都有所收獲,下面讓我們一起去探討吧!

說明

1、threading模塊具有實(shí)現(xiàn)鎖定的內(nèi)置功能,允許同步線程。為了防止數(shù)據(jù)損壞或丟失,需要鎖定來控制共享資源的訪問。

2、可以調(diào)用Lock()方法來應(yīng)用鎖,它新的鎖對(duì)象。然后,可以調(diào)用鎖對(duì)象的獲取(阻塞)方法來強(qiáng)制線程同步運(yùn)行。

實(shí)例

#Python 多線程示例來演示鎖定。
#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)注億速云行業(yè)資訊頻道,感謝各位的閱讀!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請(qǐng)聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI