Examples of the condition of Python threading

Source: Internet
Author: User

The condition object provided by Python provides support for complex thread synchronization issues. condition, called conditional variables, provides a wait and notify method in addition to the acquire and release methods that are similar to lock. The thread first acquire a condition variable and then judges some conditions. If the condition is not satisfied then wait, if the condition is satisfied, after some processing changes the condition, through the Notify method notifies other threads, other wait-state threads will be notified after the condition is again judged. Repeat this process continuously to solve the complex synchronization problem.

In addition to the above acquire method, release method, notify method, wait method There are notifyall methods, but Notifyall method is not commonly used.

51cto Blog I see a post, the image of the two-person dialogue (producer-consumer model) to explain the specific theory above.

Thread-talk

The space brother corresponding to the schematic diagram of a function, west meter corresponding to the B function, each word is doing operation, space brother not "doing" before, the West Rice need to wait. Finally, you come to me, until the end of the release, the dialogue is over. Because the code is too long, I give a compact version of the dialog that simulates the above:

#coding: Utf-8
#----Condition
#----Game of Hide-and-seek
Import threading, Time
Class Hider (threading. Thread):
def __init__ (self, cond, name):
Super (Hider, self). __init__ ()
Self.cond = Cond
Self.name = Name
def run (self):
Time.sleep (1) #确保先运行Seeker中的方法
Self.cond.acquire () #b
Print Self.name + ': I've got my eyes covered. '
Self.cond.notify ()
Self.cond.wait () #c
#f
Print Self.name + ': I Found you ~_~ '
Self.cond.notify ()
Self.cond.release ()
#g
Print Self.name + ': I won ' #h
Class Seeker (threading. Thread):
def __init__ (self, cond, name):
Super (seeker, self). __init__ ()
Self.cond = Cond
Self.name = Name
def run (self):
Self.cond.acquire ()
The self.cond.wait () #a #释放对琐的占用, while the thread hangs here until it is notify and is again occupied.
#d
Print Self.name + ': I have hidden, you come to me. '
Self.cond.notify ()
Self.cond.wait () #e
#h
Self.cond.release ()
Print Self.name + ': You found it, hey ~ ~ ~ '
Cond = Threading. Condition ()
Seeker = Seeker (cond, ' seeker ')
Hider = Hider (cond, ' Hider ')
Seeker.start ()
Hider.start ()
The results of the implementation are as follows:

[Root@361way condition]# python con3.py
Hider: I've got my eyes covered.
Seeker: I'm hiding it, you gotta come find me
Hider: I found you, ~_~.
Seeker: You found it, hey ~ ~ ~
Hider: I won.
For ease of comparison, here's an example of an infinite loop. Classic producer and consumer issues: Suppose a group of producers (Producer) and a group of consumers (Consumer) interact with one another in a market. The "strategy" of the producer is to put 100 products on the market if there are less than 1000 remaining products on the market, while the consumer's "strategy" is to consume 3 products if the number of surplus goods in the market is excess 100. The code for solving producer and consumer problems with condition is as follows:

Import threading
Import time
Class Producer (threading. Thread):
def run (self):
Global Count
While True:
If Con.acquire ():
If Count > 1000:
Con.wait ()
Else
Count = count+100
msg = self.name+ ' Produce, count= ' + str (count)
Print msg
Con.notify ()
Con.release ()
Time.sleep (1)
Class Consumer (threading. Thread):
def run (self):
Global Count
While True:
If Con.acquire ():
If Count < 100:
Con.wait ()
Else
Count = count-3
msg = self.name+ ' Consume 3, count= ' +str (count)
Print msg
Con.notify ()
Con.release ()
Time.sleep (1)
Count = 500
Con = threading. Condition ()
def test ():
For I in range (2):
p = Producer ()
P.start ()
For I in range (5):
c = Consumer ()
C.start ()
if __name__ = = ' __main__ ':
Test ()

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.