Reputation: 565
I am developing an script in which I want to have 2 threads. One of them will keep reading serial port and the other one will listen to zmq.
I want to use a queue for the first thread know when to stop reading serial port. so I want the second thread, fill a queue with a character each time it receives a message from zmq.
I already have this:
import serial import struct import threading import sys import zmq from Queue import Queue
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()
But each time the first thread reach the line with q.empty() it crashes:
TypeError: iteration over non-sequence
I also tested with a for element in q: ... but same result.
How can I consume the queue from the first thread?
Upvotes: 0
Views: 195
Reputation: 3125
TypeError
caused from for element in q:
not q.empty()
. Because Queue
class doesn't provide __iter__()
nor __getitem__()
methods for for-statement.
You should use get()
method to retrieve the element.
Upvotes: 1