#!/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)