queueLock.acquire()行挂起一段代码,该代码试图利用线程和队列模块,输出如下:
run() on <newThread(Thread-1, started 4344102912)>
run() on <newThread(Thread-2, started 4348309504)>
...working delay: 1
为什么?
import threading, thread, Queue, time
class newThread (threading.Thread):
def __init__(self, delay=0, workQueue=None):
self.delay=delay
self.workQueue=workQueue
threading.Thread.__init__(self)
def run(self):
print '\nrun() on %s'%self
print_time(self.delay, self.workQueue)
print '\nrun() exit %s'%self
def print_time(delay=None, workQueue=None):
def onExit():
if not workQueue.empty():
data = workQueue.get()
queueLock.release()
else:
queueLock.release()
counter=0
while True:
queueLock.acquire()
time.sleep(delay)
print '\t...working delay: %s'%delay
if counter>5:
onExit()
counter=counter + 1
queueLock = threading.Lock()
workQueue = Queue.Queue(10)
threads = []
thread1 = newThread(delay=1, workQueue=workQueue)
thread1.start()
threads.append(thread1)
thread2 = newThread(delay=2, workQueue=workQueue)
thread2.start()
threads.append(thread2)
queueLock.acquire()
print '1. workQueue.empty():',workQueue.empty()
workQueue.put('One')
print '2. workQueue.empty():',workQueue.empty()
workQueue.put('Two')
queueLock.release()
#Wait for queue to empty
while not workQueue.empty():
print '...passing while not workQueue.empty()'
pass
for thread in threads:
thread.join()
print '...completed'发布于 2015-10-11 04:30:40
queueLock.acquire()一直阻塞,直到queueLock.release()被调用,如果queueLock已经被获取。counter > 5从未发生,因为即使queueLock在循环的第一次迭代中可用,在第二次迭代时也不会释放它。
Queue()有自己的锁。完全放弃queueLock。
https://stackoverflow.com/questions/33060855
复制相似问题