新聞中心
這里有您想知道的互聯(lián)網(wǎng)營銷解決方案
創(chuàng)新互聯(lián)Python教程:pythonthreading線程同步如何實(shí)現(xiàn)
說明

創(chuàng)新互聯(lián)網(wǎng)站建設(shè)公司是一家服務(wù)多年做網(wǎng)站建設(shè)策劃設(shè)計制作的公司,為廣大用戶提供了網(wǎng)站建設(shè)、成都網(wǎng)站設(shè)計,成都網(wǎng)站設(shè)計,1元廣告,成都做網(wǎng)站選創(chuàng)新互聯(lián),貼合企業(yè)需求,高性價比,滿足客戶不同層次的需求一站式服務(wù)歡迎致電。
1、threading模塊具有實(shí)現(xiàn)鎖定的內(nèi)置功能,允許同步線程。
為了防止數(shù)據(jù)損壞或丟失,需要鎖定來控制共享資源的訪問。
2、可以調(diào)用Lock()方法來應(yīng)用鎖,它新的鎖對象。
可以調(diào)用鎖對象的獲取(阻塞)方法來強(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)
# 為下一個線程釋放鎖
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)
# 啟動新線程
thread1.start()
thread2.start()
# 添加線程到線程列表
threads.append(thread1)
threads.append(thread2)
# 等待所有線程完成
for thread in threads:
thread.join()
print("\nExiting the Program!!!")
以上就是python threading線程同步的實(shí)現(xiàn),希望對大家有所幫助。更多Python學(xué)習(xí)指路:創(chuàng)新互聯(lián)Python教程
本文教程操作環(huán)境:windows7系統(tǒng)、Python 3.9.1,DELL G3電腦。
本文題目:創(chuàng)新互聯(lián)Python教程:pythonthreading線程同步如何實(shí)現(xiàn)
文章路徑:http://www.dlmjj.cn/article/dpgeopi.html


咨詢
建站咨詢
