" "producers and Consumers" "" "write a multi-threaded producer and consumer producer X x>0 with Python, there's something, print (not produced) x=0, nothing, print (production) for loop consumer x x=0, nothing, print (no consumption) x>0, something, print (consumption) for loops are encapsulated as class" "ImportThreadingclassProducer (Threading. Thread):def __init__(self,name): Threading. Thread.__init__(self) self.name=namedefRun (self):Globalx tt.acquire ()ifX>0:#print ("I have finished production, you are free to go")tt.wait ()Else: forIinchRange (5): x=x+1Print("%s in production,%d"% (self.name,x))#the name of the threadtt.release ()classConsumer (Threading. Thread):def __init__(self,name): Threading. Thread.__init__(self) self.name=namedefRun (self):Globalx tt.acquire ()ifx==0:#print ("Nothing else")tt.wait ()Else: forIinchRange (5): x=x-1Print("%s in consumption,%d"% (self.name,x+1)) Tt.release () x=0#TT = Threading. Lock ()tt =Threading. Condition () P= Producer ("producer") C= Consumer ("Consumer") P.start () C.start () P.join () C.join ()
Results:
Producer in production, the 1th One
Producer in production, the 2nd one
Producer in production, the 3rd one
Producer in production, the 4th one
Producer in production, the 5th one
Consumer in consumption, the 5th one
Consumer in consumption, the 4th one
Consumer in consumption, the 3rd one
Consumer in consumption, the 2nd one
Consumer in consumption, the 1th one
It's so hard ... I'm confused.
python-Multi-Threading 3-producer Consumer