您好,登錄后才能下訂單哦!
這篇文章主要介紹“python中Event怎么實現線程間同步”的相關知識,小編通過實際案例向大家展示操作過程,操作方法簡單快捷,實用性強,希望這篇“python中Event怎么實現線程間同步”文章能幫助大家解決問題。
前言:
Event在python線程間同步是一種常用的方法,本文以生產者線程和工作者線程為例說明Event在線程間進行10次同步的應用。
import threading
from threading import Event, Thread
import time
import random
from time import sleep
pevent = Event() #默認是沒有事件的
pevent.clear()
cevent = Event()
cevent.clear()
runtimes = 10
mutex_lock = threading.Lock()
class ProducerThread (threading.Thread):
def __init__(self, name, runflag):
threading.Thread.__init__(self)
self.name = name
self.runflag = runflag
self.continueflag = Event()
self.continueflag.set()
def run(self):
global runtimes
sleep(1)
print ("開始線程:" + self.name)
while self.continueflag.isSet():
print("wait consumer ...")
if runtimes == 0:
self.continueflag.clear()
break
pevent.wait()
print("come an consumer ...")
mutex_lock.acquire()
runtimes = runtimes - 1
mutex_lock.release()
pevent.clear()
sleep(1)
cevent.set()
print ("退出線程:" + self.name)
self.runflag.set()
class ConsumerThread (threading.Thread):
def __init__(self,name, runflag):
threading.Thread.__init__(self)
self.name = name
self.runflag = runflag
self.continueflag = Event()
self.continueflag.set()
def run(self):
global runtimes
print ("開始線程:" + self.name)
while self.continueflag.isSet():
if 0 == runtimes:
self.continueflag.clear()
pevent.set()
break
print("I want to consum ... ", runtimes)
pevent.set() #通知生產者要消費
cevent.wait()
cevent.clear()
sleep(1)
print ("退出線程:" + self.name)
self.runflag.set()
def test_pthread():
runflag = Event()
pt = ProducerThread("producer", runflag)
ct = ConsumerThread("consumer", runflag)
pt.start()
ct.start()
pt.join()
ct.join()
runflag.wait()
if __name__ == '__main__':
print('===============begin=================')
test_pthread()
print('===============end=================')
關于“python中Event怎么實現線程間同步”的內容就介紹到這里了,感謝大家的閱讀。如果想了解更多行業相關的知識,可以關注億速云行業資訊頻道,小編每天都會為大家更新不同的知識點。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。