队列总是空的,即使是从Python中的另一个线程填充时也是如此

2024-09-29 20:28:16 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下代码(人为的例子):

# !/usr/bin/python

from multiprocessing import Queue
import threading
import Queue as Q
import time
from random import randint

class SomeClass:

    def takes_awhile(self, mq):
        qjson = {}
        time.sleep(5)
        qjson.update(
            {"randint": randint(1, 9)}
        )
        mq.put(qjson)

    def record(self, jq):
        while True:
            self.takes_awhile(jq)
            time.sleep(0.05)


sc = SomeClass
jq = Queue()
scp = threading.Thread(target=sc.record, args=(jq,))
scp.start()


def qprint():
    try:
        rv = jq.get_nowait()
    except Q.Empty:
        return "Empty"
    return rv


while True:
    print qprint()

我想让qprint()在被调用时总是立即返回,打印{}如果{}的时间太短,put任何东西都进入队列,但是大约5秒钟后,我应该开始看到takes_awhile(带有随机数的json)的返回值,被拉出队列。相反,无论循环运行多长时间,它总是打印Empty。在

我在这里能俯瞰什么? 任何帮助都是非常感谢的。在


Tags: fromimportselftimequeuedefemptythreading
2条回答

你的代码当前无效-我得到一个异常

TypeError: unbound method record() must be called with SomeClass instance as first argument (got Queue instance instead)

当在Thread调用中向sc.record传递参数时,没有引用SomeClass的实例,而是引用了类本身,因此self参数没有正确传递。要解决此更改,sc = SomeClass()实例化类,然后threading.Thread调用传递一个对象。在

我添加了一个while循环,使其无限期运行并打印结果。经过这些改变后,我觉得效果很好。在

输出如下:

Empty 
Empty 
Empty 
Empty 
{'randint': 4} 
Empty 
Empty

下面是我运行的代码:

^{pr2}$

你有一些小错误。您需要用sc = SomeClass()实例化某个类。你少了括号。在你的while循环中放一小段睡眠时间也是个好主意。由于打印速度太快,您无法看到非“空”语句。这是你修改过的代码。。。在

#!/usr/bin/python
from multiprocessing import Queue
import threading
import Queue as Q
import time
from random import randint

class SomeClass(object):
    def takes_awhile(self, mq):
        qjson = {}
        time.sleep(1)
        qjson.update(
            {"randint": randint(1, 9)}
        )
        mq.put(qjson)

    def record(self, jq):
        while True:
            self.takes_awhile(jq)
            time.sleep(0.05)

sc = SomeClass()
jq = Queue()
scp = threading.Thread(target=sc.record, args=(jq,))
scp.start()

def qprint():
    try:
        rv = jq.get_nowait()
    except Q.Empty:
        return "Empty"
    return rv

while True:
    print qprint()
    time.sleep(0.25)

相关问题 更多 >

    热门问题