从队列中获取值会产生' int'对象不可迭代

时间:2018-01-22 17:27:47

标签: python multithreading queue

我试图使用队列将两个变量传递给一个线程并收到错误声明' 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

当我到达该行以使该项目脱离队列时,一切都会出错。我做错了什么?

2 个答案:

答案 0 :(得分:0)

您正在使用此功能在线程版本中排队:

Speedqueue.put(spd,Direction)            

将单个项目(spd)放入队列(Direction可能被解释为block的{​​{1}}参数。在前面的非线程版本中,您使用了:

Queue.put

在这里,您将元组放入队列。但是,在这两种情况下,您的出列代码都期望一个元组已经排队。当您尝试从Speedqueue.put((spd,Dir)) 结果中分配多个值时,python假定该值是可迭代的,以便从中提取多个值。

总结:如果你想要一个元组出列,你需要将一个元组排队:

.get

答案 1 :(得分:0)

请注意传递内容的不同方式:

Speedqueue.put((spd,Dir))           # Put into the queue

您具体执行:(spd, Dir)使用这两个元素创建元组并将其作为参数传递。

当您转到线程版本时:

if spd !=0:
    Speedqueue.put(spd,Direction)                    # Write both to queue  

您正在传递:spd作为第一个参数putDirection作为第二个参数。

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  
相关问题