Question re threading and serial i/o
peter at engcorp.com
Tue Nov 4 16:51:31 CET 2003
Frank Millman wrote:
> I am not sure if this question is about threading or serial i/o - it
> has elements of both.
Definitely about both, and in various forms it's a common question.
> def scan():
> p = file('/dev/ttyS0')
> txt = 
> while x:
> ch = p.read(1)
The last line above is the heart of the problem...
> I use threading so that the user can control the program via the
> keyboard at the same time as the program is reading the serial port.
> It works ok, but I do not know how to stop it cleanly. When the user
> presses 'q' to quit, it sets a variable to tell the thread to
> terminate, but the thread is blocked at the read statement, so it does
> not know it is supposed to terminate.
> I can think of two theoretical solutions, but I do not know if either
> of them are possible.
> 1. Turn the 'read' of the serial port into a 'non-blocking' read by
> checking if there are any bytes waiting to be read before actually
> issuing the read statement. I have done this in other languages, but I
> cannot find anything in the Python documentation that explains how to
> do this.
You need to use the select.select() function with a timeout, so that
you can wake up periodically to check a flag that is set by the other
thread, asking the i/o thread to terminate. select() will return
immediately if the file has data waiting to be read, so you don't
significantly decrease the latency of the response in this way.
> 2. Have the main thread forcibly terminate the thread doing the
> reading. I cannot find anything in the Python documentation that
> explains how to do this.
Not really possible, and especially not if the i/o thread is blocked
in an external call, as it is in your case.
Variations on the above are the typical way to proceed, and generally
work fairly well.
More information about the Python-list