其他分享
首页 > 其他分享> > 第二十节 condition版生产者和消费者

第二十节 condition版生产者和消费者

作者:互联网

 1 import threading
 2 import time
 3 import random
 4 
 5 
 6 gMoney = 1000
 7 gCondition = threading.Condition()
 8 gtime = 0
 9 
10 class Producer(threading.Thread):
11     def run(self):
12         global gMoney
13         global gtime
14         while 1:
15             money = random.randint(100,1000)
16             if gtime <= 9:
17                 gCondition.acquire()
18                 gMoney += money
19                 print('%s生产了%d,账户总余额%d'%(threading.current_thread(),money,gMoney))
20                 gCondition.notify_all()
21                 gCondition.release()
22                 gtime +=1
23             else:
24                 break
25             time.sleep(0.5)
26 
27             
28 class Consumer(threading.Thread):
29     def run(self):
30         global gMoney
31         global gtime
32         while 1:
33             money = random.randint(100,1000)
34             gCondition.acquire()
35             while gMoney < money:
36                 if gtime >=10:
37                     gCondition.release()
38                     return
39                 gCondition.wait()
40             gMoney -= money
41             print('%s消费了%d,账户余额%d' % (threading.current_thread(), money, gMoney))
42             gCondition.release()
43             time.sleep(0.5)
44 
45 def main():
46     for x in range(5):
47         t = Producer()
48         t.start()
49     for x in range(5):
50         t = Consumer()
51         t.start()
52 
53 if __name__ == '__main__':
54     main()

 

标签:__,gMoney,生产者,money,gCondition,threading,gtime,第二十,condition
来源: https://www.cnblogs.com/kogmaw/p/12507047.html