首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何使用线程处理多线程

如何使用线程处理多线程
EN

Stack Overflow用户
提问于 2015-10-11 02:07:07
回答 1查看 108关注 0票数 0

queueLock.acquire()行挂起一段代码,该代码试图利用线程和队列模块,输出如下:

run() on <newThread(Thread-1, started 4344102912)>

run() on <newThread(Thread-2, started 4348309504)>

...working delay: 1

为什么?

代码语言:javascript
复制
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'
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-10-11 04:30:40

queueLock.acquire()一直阻塞,直到queueLock.release()被调用,如果queueLock已经被获取。counter > 5从未发生,因为即使queueLock在循环的第一次迭代中可用,在第二次迭代时也不会释放它。

Queue()有自己的锁。完全放弃queueLock

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/33060855

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档