我想写一个程序生产者/消费者,在这个程序中我有一个父和一个子,父填充一个共享变量与一些鱼和它发送通知在儿子。 儿子开始吃,如果没有鱼,就通知父母。 我试过这个代码,但不起作用:
import threading
import time
NUM_FISH = 13
mutex = threading.Lock()
mutParent = threading.Event()
mutSon = threading.Event()
fish = NUM_FISH
def set(fish1):
global fish
fish = fish1
def get():
return fish
def parent(mutParent, mutSon):
while True:
mutex.acquire()
mutParent.wait()
time.sleep(0.5)
try:
set(NUM_FISH)
print " + parent brings %d fish\n" % fish
mutex.release()
mutSon.set()
except:
print "Exception"
mutex.release()
def son(id, mutParent, mutSon):
while True:
mutex.acquire()
mutSon.wait()
fish = get() - 1
set(fish)
time.sleep(0.5)
try:
if fish > 0 :
print " - Son %d eats (dish: %d fish)\n" % (id, fish)
mutex.release()
else:
print " - Son %d eats (dish: %d fish) and screams\n\n" % (id, fish)
mutex.release()
mutParent.set()
except:
print "Exception"
mutex.release()
print "\n + intitial dish: %d fish\n\n" % fish
mutSon.set()
t2 = threading.Thread(target=son, args=(1, mutParent, mutSon))
t2.start()
t1 = threading.Thread(target=parent, args = (mutParent, mutSon))
t1.start()
t2.join()
t1.join()
这是我的输出:
myself@ubuntu:~/Desktop$ python a.py
+ intitial dish: 13 fish
- Son 1 eats (dish: 12 fish)
- Son 1 eats (dish: 11 fish)
- Son 1 eats (dish: 10 fish)
- Son 1 eats (dish: 9 fish)
- Son 1 eats (dish: 8 fish)
- Son 1 eats (dish: 7 fish)
- Son 1 eats (dish: 6 fish)
- Son 1 eats (dish: 5 fish)
- Son 1 eats (dish: 4 fish)
- Son 1 eats (dish: 3 fish)
- Son 1 eats (dish: 2 fish)
- Son 1 eats (dish: 1 fish)
- Son 1 eats (dish: 0 fish) and screams
- Son 1 eats (dish: -1 fish) and screams
- Son 1 eats (dish: -2 fish) and screams
- Son 1 eats (dish: -3 fish) and screams
- Son 1 eats (dish: -4 fish) and screams
- Son 1 eats (dish: -5 fish) and screams
+ parent brings 13 fish
+ parent brings 13 fish
好的,这里有三件事可以改变:
with mutex:
而不是所有的mutex.acquire()
和mutex.release()
,因为这样会自动执行,使代码更短,更不容易出错。你知道吗mutex
之前等待事件。否则线程将获取互斥锁,然后开始等待其条件变量,然而,应该设置它的线程无法获取mutex
,所以一切都停止了。注意,当有多个儿子或父母时,必须在锁定mutex
后重新检查事件。这是因为在等待事件之后,可能会在获取mutex
之前清除事件。你知道吗进行这些调整会产生以下代码:
我还没有设法打破这一点(适用于多个儿子或父母),所以我认为这是正确的,但在这一点上的任何更正都是最受欢迎的(因为这是多线程的,奇怪的事情隐藏在并行的阴影中)。你知道吗
相关问题 更多 >
编程相关推荐