我有以下代码(人为的例子):
# !/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
。在
我在这里能俯瞰什么? 任何帮助都是非常感谢的。在
你的代码当前无效-我得到一个异常
当在
Thread
调用中向sc.record
传递参数时,没有引用SomeClass
的实例,而是引用了类本身,因此self
参数没有正确传递。要解决此更改,sc = SomeClass()
实例化类,然后threading.Thread
调用传递一个对象。在我添加了一个
while
循环,使其无限期运行并打印结果。经过这些改变后,我觉得效果很好。在输出如下:
下面是我运行的代码:
^{pr2}$你有一些小错误。您需要用
sc = SomeClass()
实例化某个类。你少了括号。在你的while循环中放一小段睡眠时间也是个好主意。由于打印速度太快,您无法看到非“空”语句。这是你修改过的代码。。。在相关问题 更多 >
编程相关推荐