Python 线程(三):Condition(条件变量)

    条件变量是属于线程的高级应用,所以我们一般需要引入threading模块,而在条件变量中,最经典的例子,恐怕就是生产者与消费者的问题了。

  Condition:  一个比Lock, RLock更高级的锁

  wait:    等待被唤醒

  notify/notifyAll : 唤醒一个线程,或者唤醒所有线程

  注意:Condition,在wait之前必须require

  代码:

 1 import threading
 2 import time
 3 
 4 class Buf:
 5     def __init__(self):
 6 
 7         self.cond = threading.Condition()
 8         self.data = []
 9 
10     def isFull(self):
11         return len(self.data) == 5
12 
13     def isEmpty(self):
14         return len(self.data) == 0
15 
16     def get(self):
17 
18         self.cond.acquire()
19 
20         while self.isEmpty():
21             self.cond.wait()
22 
23         temp = self.data.pop(0)
24 
25         self.cond.notify()
26         self.cond.release()
27         return temp
28 
29     def put(self, putInfo):
30         self.cond.acquire()
31 
32         while self.isFull():
33             self.cond.wait()
34 
35         self.data.append(putInfo)
36 
37         self.cond.notify()
38         self.cond.release()
39 
40 
41 def Product(num):
42     for i in range(num):
43         info.put(i+1)
44         print "Product %s\n" % (str(i+1))
45 
46 def Customer(id, num):
47     for i in range(num):
48         temp = info.get()
49         print "Customer%s %s\n" % (id, str(temp))
50 
51 info = Buf();
52 
53 
54 if __name__ == "__main__":
55     p = threading.Thread(target=Product, args=(10, ))
56     c1 = threading.Thread(target=Customer, args=('A', 5))
57     c2 = threading.Thread(target=Customer, args=('B', 5))
58 
59     p.start()
60     time.sleep(1)
61     c1.start()
62     c2.start()
63 
64     p.join()
65     c1.join()
66     c2.join()
67 
68     print "Game Over"

 

  

转载于:https://www.cnblogs.com/wang-can/p/3581230.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值