日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

python中Event實現線程間同步介紹_python

作者:hsy12342611 ? 更新時間: 2022-06-11 編程語言

前言:

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=================')

運行結果如下:

原文鏈接:https://blog.csdn.net/hsy12342611/article/details/124065314

欄目分類
最近更新