get中的生产者消费者锁定了get

时间:2015-06-16 22:12:31

标签: python multithreading python-3.x

我正在努力在Python3中创建一个生产者消费者队列。我不能让我的消费者醒来:

from multiprocessing import Process, Queue
import time
def consumer(q):
        while(True):
            data=q.get()
            if (data[0]==False):
                print("Killing")
                return
            print((data[1]))
            time.sleep(1)

maxitems=3
q = Queue(maxitems)
p = Process(target=consumer, args=(q,))
p.start()
for idx in range(0,10):
    q.put((True,idx))
    #Where idx would normally be a chunk of data
p.put((False,False))
p.join()

输出:

0

然后锁定......

当我向其推送数据时,如何让消费者线程唤醒?

启动:

python3.3 tryit.py

内置:

[ebuild   R    ] dev-lang/python-3.3.5-r1:3.3::gentoo  USE="gdbm ipv6 ncurses readline ssl threads xml -build -doc -examples -hardened -sqlite -tk -wininst" 0 KiB

2 个答案:

答案 0 :(得分:0)

p.put((False,False))是错误的,而且是一些非惯用的Python,否则它很好。

from multiprocessing import Process, Queue
import time

def consumer(q):
        while True:
            data=q.get()
            if data[0]==False:
                print("Killing")
                break
            print(data[1])
            time.sleep(1)

maxitems=3
q = Queue(maxitems)
p = Process(target=consumer, args=(q,))
p.start()
for idx in range(0,10):
    q.put((True,idx))
    #Where idx would normally be a chunk of data
q.put((False,False))
p.join()                                                                                                               

答案 1 :(得分:0)

不知何故,这需要从主要

运行
from multiprocessing import Process, Queue
import time
def consumer(q):
         while(True):
            data=q.get()
            if (data[0]==False):
                print("Killing")
                return
            print((data[1]))
            time.sleep(1)

if __name__ == '__main__':
    maxitems=3
    q = Queue(maxitems)
    p = Process(target=consumer, args=(q,))
    p.start()
    for idx in range(0,10):
        q.put((True,idx))
        #Where idx would normally be a chunk of data
    q.put((False,False))
    p.join()