Python multithreaded Programming (vii): Using Condition for complex synchronization

Source: Internet
Author: User
We have now used lock to mutually exclusive access to public resources, but also discussed that the same thread can use Rlock to re-enter the lock, but even though we only deal with the simple synchronization of some programs, we are not even reasonable to solve the deadlock caused by using lock lock problem. So we have to learn to use a deeper approach to solving synchronization problems.

The condition object provided by Python provides support for complex thread synchronization issues. condition is called a conditional variable and provides the wait and notify methods in addition to the acquire and release methods similar to lock.

The main way to use condition is that the thread first acquire a condition variable and then determines some conditions. Wait if the condition is not met, and if the condition is met, after some processing changes the condition, the other thread is notified by the Notify method, and the other thread in the wait state will be re-judged after receiving the notification. Constantly repeating this process to solve complex synchronization problems.

Below we demonstrate with a well-known "producer-consumer" model, using condition in Python for complex synchronization.
Copy the Code code as follows:


'''
Created on 2012-9-8

@author: walfred
@module: Thread. TreadTest7
'''

Import threading
Import time

Condition = Threading. Condition ()
Products = 0

Class Producer (threading. Thread):
def __init__ (self):
Threading. Thread.__init__ (self)

def run (self):
Global condition, Products
While True:
If Condition.acquire ():
If products < 10:
Products + = 1;
Print "Producer (%s):d Eliver One, now products:%s"% (self.name, products)
Condition.notify ()
Else
Print "Producer (%s): Already, stop deliver, now products:%s"% (self.name, products)
Condition.wait ();
Condition.release ()
Time.sleep (2)

Class Consumer (threading. Thread):
def __init__ (self):
Threading. Thread.__init__ (self)

def run (self):
Global condition, Products
While True:
If Condition.acquire ():
If products > 1:
Products-= 1
Print "Consumer (%s): Consume one, now products:%s"% (self.name, products)
Condition.notify ()
Else
Print "Consumer (%s): Only 1, stop consume, products:%s"% (self.name, products)
Condition.wait ();
Condition.release ()
Time.sleep (2)

if __name__ = = "__main__":
For P in range (0, 2):
p = Producer ()
P.start ()

For C in range (0, 10):
c = Consumer ()
C.start ()

The main implementation of the code in the producer and consumer threads, the two sides will be around the products to create synchronization problems, first of all, 2 generators to produce product, and then the next 10 consumers will be consumed, the code runs as follows:

Copy the Code code as follows:


Producer (Thread-1):d Eliver One, now products:1
Producer (Thread-2):d Eliver One, now Products:2
Consumer (Thread-3): Consume one, now products:1
Consumer (Thread-4): Only 1, stop consume, products:1
Consumer (Thread-5): Only 1, stop consume, products:1
Consumer (Thread-6): Only 1, stop consume, products:1
Consumer (Thread-7): Only 1, stop consume, products:1
Consumer (Thread-8): Only 1, stop consume, products:1
Consumer (THREAD-10): Only 1, stop consume, products:1
Consumer (Thread-9): Only 1, stop consume, products:1
Consumer (Thread-12): Only 1, stop consume, products:1
Consumer (Thread-11): Only 1, stop consume, products:1


In addition: the constructor of the condition object can accept a Lock/rlock object as a parameter, and if not specified, the condition object creates a rlock on its own, except for the Notify method. The condition object also provides a Notifyall method that notifies all threads in the waiting pool to attempt to acquire an internal lock. As a result of the above mechanism, threads in the waiting state can only be awakened by the Notify method, so the role of notifyall is to prevent the thread from ever being in a state of silence.
  • 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.