条件变量是属于线程的高级应用,所以我们一般需要引入threading模块,而在条件变量中,最经典的例子,恐怕就是生产者与消费者的问题了。
Condition: 一个比Lock, RLock更高级的锁
wait: 等待被唤醒
notify/notifyAll : 唤醒一个线程,或者唤醒所有线程
注意:Condition,在wait之前必须require
代码:
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68 |
import
threadingimport
timeclass
Buf: def
__init__(self): self.cond =
threading.Condition() self.data =
[] def
isFull(self): return
len(self.data) ==
5 def
isEmpty(self): return
len(self.data) ==
0 def
get(self): self.cond.acquire() while
self.isEmpty(): self.cond.wait() temp =
self.data.pop(0) self.cond.notify() self.cond.release() return
temp def
put(self, putInfo): self.cond.acquire() while
self.isFull(): self.cond.wait() self.data.append(putInfo) self.cond.notify() self.cond.release()def
Product(num): for
i in
range(num): info.put(i+1) print
"Product %s\n" %
(str(i+1))def
Customer(id, num): for
i in
range(num): temp =
info.get() print
"Customer%s %s\n" %
(id, str(temp))info =
Buf();if __name__ ==
"__main__": p =
threading.Thread(target=Product, args=(10, )) c1 =
threading.Thread(target=Customer, args=(‘A‘, 5)) c2 =
threading.Thread(target=Customer, args=(‘B‘, 5)) p.start() time.sleep(1) c1.start() c2.start() p.join() c1.join() c2.join() print
"Game Over" |
Python 线程(三):Condition(条件变量),布布扣,bubuko.com
原文:http://www.cnblogs.com/wang-can/p/3581230.html