Methods for thread synchronization using queue and condition in Python

Source: Internet
Author: User
Queue module keeps thread synchronized
Using the Queue object's FIFO feature, each producer's data is saved to the queue one at a time, and each consumer pulls the data from the queue sequentially

Import Threading # Imports Threading Module Import Queue # Imports the Queue module class Producer (threading. Thread): # defines the producer class Def __init__ (self,threadname): Threading. thread.__init__ (Self,name = threadname) def run (self): Global Queue # declares that the queue is a global variable queue.put (Self.getname ()) # Call The Put method adds the thread name to the queue print self.getname (), ' Put ', self.getname (), ' to Queue ' class Consumer (threading. Thread): # Defines consumer class Def __init__ (self,threadname): Threading. thread.__init__ (Self,name = threadname) def run (self): Global queue Print self.getname (), ' Get ', Queue.get (), ' from Q ' Ueue ' #调用get方法获取队列中内容queue = Queue.queue () # Build Queue Object plist = [] # Creator Object list clist = [] # Consumer Object list for I in range: p = Pr Oducer (' Producer ' + str (i)) Plist.append (P) # Add to Producer object list for I in range: c = Consumer (' Consumer ' + str (i)) clist.a Ppend (c) # Add to Consumer object list for I in Plist:i.start () # Run producer Thread I.join () for I in Clist:i.start () # Run consumer thread I.join () # # # # # # #运行结果 ######>>> Producer0 put Producer0 to QueueProducer1 put ProduCer1 to QueueProducer2 put Producer2-QueueProducer3 put Producer3 to QueueProducer4 put Producer4 to QueueProducer5 put Producer5 to QueueProducer6 put Producer6-QueueProducer7 put Producer7 to QueueProducer8 put Producer8 to Queueproduce R9 put Producer9 to QueueConsumer0 get Producer0 from QueueConsumer1 get Producer1 from QueueConsumer2 get Producer2 from QueueConsumer3 get Producer3 from QueueConsumer4 get Producer4 from QueueConsumer5 get Producer5 from QueueConsumer6 get P Roducer6 from QueueConsumer7 get Producer7 from QueueConsumer8 get Producer8 from QueueConsumer9 get Producer9 from queue

Condition to achieve complex synchronization
The condition object can be used to process data after certain events have been triggered or to meet certain conditions, condition in addition to the acquire method and the release method with the lock object,
There are wait methods, notify methods, Notifyall methods, and so on for conditional processing.
Conditional variables Keep thread synchronized: threading. Condition ()

    • Wait (): thread hangs until a notify notification is received before it wakes up and continues to run
    • Notify (): Notifies other threads that the suspended thread will start running after receiving this notification
    • Notifyall (): If the wait state thread is more, the Notifyall is to notify all threads (this is generally used less)
#coding: utf-8import threadingimport timecond = Threading. Condition () class Kongbaige (threading. Thread): Def __init__ (self, cond, Diaosiname): Threading. Thread.__init__ (self, name = diaosiname) Self.cond = Cond def run (self): Self.cond.acquire () #获取锁 PR int self.getname () + ': A pierce Arrow ' #空白哥说的第一句话 self.cond.notify () #唤醒其他wait状态的线程 (notify Cimetidine to let him speak) #然后进入wait线程挂起状态等待not    Ify notice (and so on the reply, the next two people began to pull eggs) self.cond.wait () print self.getname () + ': Mountain without edges, heaven and earth together, is dare and June absolutely! ' Self.cond.notify () self.cond.wait () print self.getname () + ': Crape Myrtle!!! (picture omitted here) ' Self.cond.notify () self.cond.wait () print self.getname () + ': Yes You ' self.cond.notify () self.co Nd.wait () #这里是空白哥说的最后一段话, and then there was no dialogue. Print Self.getname () + ': money to Borrow ' self.cond.notify () #通知西米哥 Self . Cond.release () #释放锁 class Ximige (threading. Thread): Def __init__ (self, cond, Diaosiname): Threading. Thread.__init__ (self, name = Diaosiname) Self.conD = Cond def run (self): Self.cond.acquire () self.cond.wait () #线程挂起 (notify notice) print Self.getnam E () + ': a mighty Army to meet ' self.cond.notify () #说完话了notify空白哥wait的线程 self.cond.wait () #线程挂起等待空白哥的notify通知 print SELF.G Etname () + ': The sea can wither, the stone can rot, the passion never scattered! ' Self.cond.notify () self.cond.wait () print self.getname () + ': er kang!!! (picture omitted here) ' Self.cond.notify () self.cond.wait () print self.getname () + ': It's Me ' self.cond.notify () self.co Nd.wait () #这里是最后一段话, the back blank brother did not answer, so finish release lock end thread print self.getname () + ': Roll ' self.cond.release () Kon Gbai = Kongbaige (Cond, ') Ximi = Ximige (cond, ' Sago ') #尼玛下面这2个启动标志是关键, although the opening of the empty brother first, but can not let him start first, #因为他先启动的可能直到发完notify通知了, Cimetidine began to start, #西米哥启动后会一直处于44行的wait状态, because the blank elder brother has been sent notify notice into the wait state, #而西米哥没收到 # cause the result is 2 threads have been hanging, nothing is dry, also do not pull eggs ximi.start ( ) Kongbai.start ()

##### #运行结果 ######

  : A pierce Arrow Sago: A mighty force to meet  : Mountain without Edge, heaven and earth together, is dare and June absolutely! Sago: The sea can be withered, the stone can rot, the passion never scattered!  : Crape Myrtle!!! (picture omitted here) cimetidine: er kang!!! (picture omitted here)  : It's you. Sago: It's me: Is there  money to borrow? Sago: Roll
  • Related Article

    Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.