<p>我在你的代码中添加了一些注释,这有一些问题:</p>
<pre><code>def run(self):
while True:
customer=Customer()
self.mutex.acquire()
if self.queue.full():
print "Queue is full : Cant Enter Critical Section"
# NOTE 1: you have to release mutex here: self.mutex.release()
elif not self.queue.full():
# NOTE 2: other threads can enter after releasing the lock
print self.mutex.release()
self.mutex.acquire()
#Critical Section
self.queue.put(customer)
print "Customer %d Enters the Queue with %d service " %(
customer.id,customer.serviceTime
)
self.mutex.release()
</code></pre>
<p>除了注1之外(但动机相同):</p>
<pre><code>def run(self):
while True:
customer=Customer()
self.mutex.acquire()
if self.queue.full():
print "Queue is full : Cant Enter Critical Section"
elif not self.queue.full():
# NOTE 2: other threads can enter after releasing the lock
print self.mutex.release()
self.mutex.acquire()
#Critical Section
self.queue.put(customer)
print "Customer %d Enters the Queue with %d service " %(
customer.id,customer.serviceTime
)
# Note 1 alternative - release mutex (cancel 'if' branching effect)
self.mutex.release()
</code></pre>
<p>我真的不明白这是逻辑。您释放了锁,允许线程检查队列,而其他线程推送到队列,但您认为队列不是线程安全的。</p>
<p>如果使用的是队列的线程安全性,那么为什么首先使用互斥锁?</p>
<p><strong>编辑:</strong>主要问题是,正如指定的那样,您要与生产者获取两次互斥量。只能获取互斥对象一次(至少当它是<code>threading.Lock</code>对象时)。在您的对讲机中尝试以下代码:</p>
<pre><code>>>> import threading
>>> lock = threading.Lock()
>>> lock.acquire()
True
>>> lock.acquire()
</code></pre>
<p>看看会发生什么。</p>
<p>不管怎样,找出关键部分的逻辑。固定代码(注意1)应该可以防止由于在第一个if分支上没有释放互斥锁而导致的阻塞。</p>
<p>祝你好运。</p>