可以使用锁来负责互斥,使用threading.Condition来做同步。threading的完整用法见官方文档,Condition的完整用法见Condition的描述。简单来说,Condition内置了锁,当调用acquire()方法时,自动上锁,release()释放锁。wait()方法会释放锁后阻塞程序,直到被notify()方法唤醒。Talk is cheap, this is the code.
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
#!/usr/bin/env python
# -*- coding:utf-8 -*-
import threading
import random
import time
warehouse = []
max_num = 10
condition = threading.Condition()
classProducerThread(threading.Thread):
def__init__(self):
threading.Thread.__init__(self)
defrun(self):
whileTrue:
condition.acquire()
if len(warehouse) == max_num:
print"Warehouse is full"
condition.wait() # Release the lock
print"Producer is notified by consumer"
else:
warehouse.append(1)
print"Producer is working, NUM: " + str(len(warehouse))
condition.notify()
condition.release()
time.sleep(random.random())
classConsumerThread(threading.Thread):
def__init__(self):
threading.Thread.__init__(self)
defrun(self):
whileTrue:
condition.acquire()
if len(warehouse) == 0:
print"Warehouse is empty"
condition.wait()
print"Consumer is notified by producer"
else:
warehouse.pop()
print"Consumer is working, NUM: " + str(len(warehouse))
Note: the notify() and notifyAll() methods don’t release the lock; this means that the thread or threads awakened will not return from their wait() call immediately, but only when the thread that called notify() or notifyAll() finally relinquishes ownership of the lock.