Python Basics-Condition variables

Source: Internet
Author: User

There is a class of threads that need to meet the criteria before they can proceed, and Python provides support for the Threading.condition object for the conditional variable thread, which, in addition to providing a rlock () or lock () method, also provides wait (), notify (), Notifyall () method.

Lock_con=threading. Condition ([Lock/rlock]): The lock is an optional option, does not pass in the lock, and the object automatically creates a Rlock ().

    • Wait (): Called when the condition is not satisfied, the thread releases the lock and enters the waiting block
    • Notify (): Called after condition creation, notifies the waiting pool to activate a thread
    • Notifyall (): Called after condition creation, notifies the waiting pool to activate all threads
import threading,timefrom random import Randintclass Producer (threading. Thread): def run (self): global L while True:val=randint (0,100) print (' producer ', self.na                Me, ": Append" +str (val), L) if Lock_con.acquire (): L.append (val) lock_con.notify () Lock_con.release () Time.sleep (3) class Consumer (threading.                Thread): def run (self): global L while True:lock_con.acquire () If Len (L) ==0: Lock_con.wait () print (' Consumer ', Self.name, ':D elete ' +str (l[0]), L) del l[0] Lock_con. Release () Time.sleep (0.25) if __name__== "__main__": l=[] lock_con=threading.    Condition () #创建条件变量锁 threads=[] for I in range (5): Threads.append (Producer ()) Threads.append (Consumer ()) For T in Threads: #启动5个生产, 1 Consumer thread Objects T.start () for T in Threads:t.join () 

Python Basics-Condition variables

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.