Reputation: 2529
I am trying to create a one thread to listen for incoming data from COM serial port while main thread is doing some operation.
Here is my code (some codes are omitted for brevity) :
def readMsg( serial ):
msgArray = []
while ( True ):
char = "0x" + serial.read().encode('hex')
if char == '0xfd':
msgArray = []
msgArray.append(char)
elif char == '0xfc':
msgArray.append(char)
print debugPrefix, "ComPort:", (serial.port + 1), msgArray
elif char == '0x':
pass
else:
msgArray.append(char)
# Find available ports
initializeComPorts()
# Print port infos
printComPorts()
# Opens serial and returns opened serial
serialPort = openPort(1);
print "thread started"
readMsgThread = threading.Thread( target=readMsg(serialPort) )
readMsgThread.setDaemon( True )
readMsgThread.start()
print "sending some data"
serialPort.send('h')
When I execute the code readMsgThread
listens fine, but the line print "sending some data"
is never executed. Can someone please explain what am I missing? I've been stuck at this for a while.
Thanks you very much.
Upvotes: 3
Views: 690
Reputation: 70715
I can't test this for you, but think carefully about this line:
readMsgThread = threading.Thread( target=readMsg(serialPort) )
That calls readMsg(serialPort)
at the time the assignment is excecuted, and passes the result as target
. I'm guessing you almost certainly want to do:
readMsgThread = threading.Thread( target=readMsg, args=(serialPort,) )
instead.
To clarify a little more, because you're calling readMsg
on that line, no further lines will be executed until readMsg
returns. But that function never returns. That's why "sending some data" is never seen. In fact, you never get to the
readMsgThread.setDaemon( True )
statement either.
Upvotes: 8