How to realize synchronization between threads in Event in python
This article mainly introduces the relevant knowledge of "how to achieve inter-thread synchronization in python". The editor shows you the operation process through an actual case. The operation method is simple, fast and practical. I hope this article "how to achieve inter-thread synchronization in Event in python" can help you solve the problem.
Foreword:
Event synchronization between python threads is a common method. This paper takes producer thread and worker thread as an example to illustrate the application of Event synchronization between threads for 10 times.
Import threading
From threading import Event, Thread
Import time
Import random
From time import sleep
Pevent = Event () # there are no events by default
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 ("start thread:" + 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 ("exit thread:" + 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 ("start thread:" + self.name)
While self.continueflag.isSet ():
If 0 = = runtimes:
Self.continueflag.clear ()
Pevent.set ()
Break
Print ("I want to consum...", runtimes)
Pevent.set () # notifies the producer to consume
Cevent.wait ()
Cevent.clear ()
Sleep (1)
Print ("exit thread:" + 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=')
This is the end of the content about "how to achieve inter-thread synchronization in Event in python". Thank you for reading. If you want to know more about the industry, you can follow the industry information channel. The editor will update different knowledge points for you every day.