如何使用线程进行多线程处理

时间:2015-10-11 02:07:07

标签: python multithreading

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'

1 个答案:

答案 0 :(得分:2)

如果已经获得queueLock.acquire(),则在queueLock.release()之前阻止

queueLock阻止。 counter > 5永远不会发生,因为即使queueLock在循环的第一次迭代中可用;在第二次迭代中没有发布它。

Queue()有自己的锁。完全删除queueLock