>我正在尝试使用队列将两个变量传递给线程,并收到一条错误消息,指出"int"对象不可迭代。
首先,我尝试在不线程的情况下将 100 个值放入队列中,只是为了检查我可以放入和获取。这是执行此操作的代码(有效(。
for i in range(100):
spd,Dir=CalcSpeed() # Get speed and direction
Speedqueue.put((spd,Dir)) # Put into the queue
sleep(0.1) # Wait a bit before repeating
UpdateBar(spd,Dir) # Update the graphics
for i in range(100):
Spd,Dir=Speedqueue.get() # De-queue item
run_loop(Spd,Dir) # Run motor at required speed and direction
然后我转到线程版本并将值放入队列中,如下所示:
if spd !=0:
Speedqueue.put(spd,Direction) # Write both to queue
然后我尝试像这样恢复队列的内容:
class Worker(Thread):
def __init__(self, queue):
Thread.__init__(self)
self.queue=queue
def run(self):
while True:
if self.queue.empty():
pass
else:
Spd,Direction=self.queue.get() # otherwise get results from queue
last_Speed=Spd # and update last values
lastDirection=Direction
当我排队将物品从队列中取出时,一切都出错了。请问我做错了什么?
你正在使用它来排队进入线程版本:
Speedqueue.put(spd,Direction)
它将单个项目(spd
(放入队列(Direction
可能被解释为Queue.put
的block
参数(。在前面的非线程版本中,您使用了:
Speedqueue.put((spd,Dir))
在这里,您将一个元组放入队列中。但是,在这两种情况下,您的出列代码都期望元组已排队。当你尝试从.get
结果中分配多个值时,python 假设该值是可迭代的,以便从中提取多个值。
摘要:如果要取消元组的排队,则需要将元组排队:
Speedqueue.put((spd, Direction))
注意传递内容的不同方式:
Speedqueue.put((spd,Dir)) # Put into the queue
你具体要做的是:(spd, Dir)
创建一个包含两个元素的元组,并将其作为参数传递。
当您转到线程版本时:
if spd !=0:
Speedqueue.put(spd,Direction) # Write both to queue
您正在传递:spd
作为put
的第一个参数,Direction
作为第二个参数。
put
的签名是:
Queue.put(item[, block[, timeout]](
请参阅文档(适用于 2.x,但适用于 3.x(:https://docs.python.org/2/library/queue.html#Queue.Queue.put
在函数调用之外,确实如此: spd,Direction
将导致一个元组,但在这种情况下,每个项目都被解释为一个项目,因此被推入队列的实际内容是:spd
这是一个int
而不是可迭代的。因此,请:
if spd !=0:
Speedqueue.put((spd,Direction)) # Write both to queue