In Python, the Queue and Condition are used for thread synchronization.

Source: Internet
Author: User

In Python, the Queue and Condition are used for thread synchronization.

The Queue module maintains thread synchronization.
Using the first-in-first-out feature of the Queue object, the data of each producer is stored in the Queue at a time, and each consumer extracts data from the Queue in sequence.

Import threading # import the threading module import Queue # import the Queue module class Producer (threading. thread): # define the producer class def _ init _ (self, threadname): threading. thread. _ init _ (self, name = threadname) def run (self): global queue # declare the queue as the global variable queue. put (self. getName () # Call the put Method to add the thread name to the queue print self. getName (), 'put', self. getName (), 'to queue' class Consumer (threading. thread): # define the consumer class def _ init _ (self, threadname): threading. thread. _ init _ (self, name = threadname) def run (self): global queue print self. getName (), 'get', queue. get (), 'From queue '# Call the get method to obtain the queue content Queue = queue. queue () # generate Queue object plist = [] # generate Object List clist = [] # consumer object list for I in range (10 ): p = Producer ('producer '+ str (I) plist. append (p) # add to the producer Object List for I in range (10): c = Consumer ('consumer '+ str (I) clist. append (c) # Add to consumer object list for I in plist: I. start () # Run the producer thread I. join () for I in clist: I. start () # Run consumer thread I. join () ###### running result #######>> Producer0 put Producer0 to queueProducer1 put Producer1 to queueProducer2 put Producer2 to queueProducer3 put Producer3 to producer put Producer4 to producer put Producer5 to convert put Producer6 to convert put Producer7 to queueProducer8 put Producer8 to queueProducer9 put Producer9 to batch get Producer0 from batch get Producer1 from batch get Producer2 from batch get Producer3 from batch get Producer4 from queueConsumer6 get Producer6 from queueConsumer7 get Producer7 from queueConsumer8 get Producer8 from queueConsumer9 get Producer9 from queue

Condition for complex Synchronization
The Condition object can be used to process data only when certain events are triggered or when specific conditions are met. In addition to the acquire method and release method with Lock objects,
The wait, y, and yyall methods are also used for conditional processing.
Condition variables keep thread synchronization: threading. Condition ()

  • Wait (): The thread is suspended until it receives a notify y notification.
  • Y (): notifies other threads that the suspended threads will start running after receiving the notification.
  • Yyall (): if there are many threads in the wait Status, notifyAll is used to notify all threads (this is usually 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 () # obtain the lock print self. getName () + ': an arrow in the cloud # The first sentence self. cond. Y () # Wake up other threads in the wait state (notify simi to let him talk) # Then enter the wait thread to suspend the state and wait for the notify notification (wait for simi's reply, the next two will start to get involved.) self. cond. wait () Print self. getName () + ': the mountains have no borders, and the sky and the earth are combined! 'Self. cond. Every y () self. cond. wait () print self. getName () + ': Ziwei !!!! (The image is omitted here) 'self. cond. policy () self. cond. wait () print self. getName () + ': You are 'self. cond. policy () self. cond. wait () # here is the last line that the white space brother said, and then there is no print self. getName () + ': Do you have money? Borrow 'self. cond. notify () # notify simi self. cond. release () # release lock 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. con D. wait () # thread suspension (wait for ximi's notify notification) print self. getName () + ': meet each other 'self. cond. Y () # finished talking about the thread self of the blank brother wait of notify. cond. wait () # The thread hangs and waits for the blank brother to notify print self. getName () + ': the sea can be dry, the rock can be rotten, and the passion will never go away! 'Self. cond. Consumer y () self. cond. wait () print self. getName () + ': Er Kang !!! (The image is omitted here) 'self. cond. policy () self. cond. wait () print self. getName () + ': Yes, 'self. cond. policy () self. cond. wait () # here is the last paragraph. The white-space brother will release the lock end thread print self. getName () + ': Roll 'self. cond. release () kongbai = kongbaige (cond, '') ximi = ximige (cond, 'ximi') # The two startup marks below Nima are key, although it is the first interface opened by the blank brother, he cannot start it first. # because it is possible that he may start it first until the notify y is sent, but ximi will start it, # After ximigo is started, it will remain in the wait Status of 44 rows, because the blank brother has sent notify notifications to enter the wait status, # The result is that the two threads have been suspended there, and everything is not done. ximi. start () kongbai. start ()

###### Running result ######

: A Cross-cloud arrow ximi: qianjun Wanma to meet: the mountains have no borders, heaven and earth together, but dare to absolutely! Ximi: the sea can be dry, the stone can be rotten, and the passion will never go away! : Ziwei !!!! (The picture is omitted here) ximi: erkang !!! (The picture is omitted here): It's your ximi: It's me: do you have money? Borrow some ximi: Roll

Articles you may be interested in:
  • Python multi-thread synchronization Lock, RLock, Semaphore, Event instance
  • Python multi-thread programming (7): using Condition for complex Synchronization
  • Python multi-process synchronization Lock, Semaphore, Event instance

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.