Python multi-thread condition (condition variable)

Source: Internet
Author: User

#!/usr/bin/env python#-*-coding:utf-8-*- fromThreadingImportThread, ConditionImportTimeitems=[]condition=Condition ()classConsumer (Thread):def __init__(self): Thread.__init__(self)defconsume (self):GlobalconditionGlobalItems Condition.acquire ()ifLen (items) = =0:condition.wait ()Print("Consumer notify:no item to consume") Items.pop ()Print("Consumer notify:consumed 1 Item")        Print("Consumer Nofity:items to consume is"              +str (len (items))) condition.notify () condition.release ()defRun (self): forIinchRange (0, 20): Time.sleep (4) Self.consume ()classProducer (Thread):def __init__(self): Thread.__init__(self)defProduce (self):GlobalconditionGlobalItems Condition.acquire ()ifLen (items) = = 10: condition.wait ()Print("Producer Notify:item producted is"                   +str (len (items )))Print("Producer nofity:stop the production!!") Items.append (1)        Print("Producer nofity:total Items producted"              +str (len (items))) condition.notify () condition.release ()defRun (self): forIinchRange (0, 20): Time.sleep (1) self.produce ()if __name__=="__main__": Producer=Producer () consumer=Consumer () Producer.start () Consumer.start () Producer.join () Consumer.join ()

Python multi-thread condition (condition variable)

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.