【问题标题】:Consume queue from other thread从其他线程消费队列
【发布时间】:2015-03-23 09:59:38
【问题描述】:

我正在开发一个脚本,其中我想要有 2 个线程。其中一个将继续读取串口,另一个将监听 zmq。

我想使用一个队列让第一个线程知道何时停止读取串行端口。所以我想要第二个线程,每次收到来自 zmq 的消息时,用一个字符填充一个队列。

我已经有了这个:

导入序列号 导入结构 导入线程 导入系统 导入zmq 从队列导入队列

  ser = serial.Serial('/dev/ttyUSB0', 38400)
  port = "5556"

  q = Queue(maxsize=0)
  #q = []

  context = zmq.Context()
  socket = context.socket(zmq.SUB)
  socket.connect("tcp://localhost:%s"% port)
  socket.setsockopt(zmq.SUBSCRIBE,'')

  class ReadingThread(threading.Thread):
    def __init__(self):
      super(ReadingThread, self).__init__()
    def run(self):
      while True:
        if q.empty() == False:
            for element in q:
              print element
        data= ser.read()          print "INT", data

  class ZMQThread(threading.Thread):
    def __init__(self):
      super(ZMQThread, self).__init__()
    def run(self):
      while True:
        msg = socket.recv()
        #print "RECIBIDO"
        q.put(msg)

  thread1 = ReadingThread()
  thread1.start()
  thread2 = ZMQThread()
  thread2.start()

但每次第一个线程到达 q.empty() 的行时,它都会崩溃:

TypeError: iteration over non-sequence

我还在 q: ... 中使用 for 元素进行了测试,但结果相同。

如何使用第一个线程的队列?

【问题讨论】:

    标签: python multithreading queue


    【解决方案1】:

    TypeErrorfor element in q: 而非 q.empty() 引起。因为Queue 类没有提供__iter__()__getitem__() for 语句的方法。

    您应该使用get() 方法来检索元素。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-08-04
      • 2015-09-08
      • 2018-03-08
      • 2021-11-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-11-15
      相关资源
      最近更新 更多