[Tutor] threading in python2.7
joseph.lee22590 at gmail.com
Fri Jan 2 21:39:36 CET 2015
Answers are below.
From: Tutor [mailto:tutor-bounces+joseph.lee22590=gmail.com at python.org] On
Behalf Of Rance Hall
Sent: Friday, January 2, 2015 12:17 PM
Subject: [Tutor] threading in python2.7
Each of the lights and sound functions are placed in a "while not exitFlag:"
I think I'm running into some variable scoping issues related to threads,
but I'm not sure exactly.
JL: Each thread has its own context and local variables unless you want to
bring in the exit flag from the module itself. A good place to do it is
right before you enter the while loop.
Based on the debugging messages I've added to my code, the changes to the
exitFlag variable made in the either the main loop or the cleanup loop are
never seen by the lights and sound loop threads.
The net effect of this is that once the threads are started, they are
uncontrollable and I have to quit the terminal to get the threads to stop.
Could someone please point me in the direction of a good tutorial or sample
code that works that I could use as study tool?
JL: There are plenty of projects online which uses threads. A toy project
might be to implement a long running counter that stops when you set some
variable to False, like:
stop = False
for i in xrange(upto):
if stop: return
t = threading.Thread(count, args=(someNumber))
Essentially, this guy runs two threads: the main thread, and the counter
thread. If the stop value is set, the counter thread will stop running. As
for placing the value check at the top of the loop, it was done that way to
make sure the thread dies when it is true and to do it as early as possible
Threads introduce interesting issues. For instance, due to Python's global
interpreter lock (GIL), only one thread can run at a given time. You'll also
need to make sure that values modified by one thread is not misinterpreted
in other threads, and that two or more threads doesn't write to same
location at the same time and cause problems (the way to mitigate this is
using what's called "critical region" where only one thread at a time can
mess with an important variable or do some critical activity, quite beyond
the scope I think).
I've not bothered posting the code since its custom to this board and will
fail on another python instance unless it has the the same hardware control
modules my board does.
JL: If you are writing for an embedded board and want to really make sure
your code will work as intended, try starting from your desktop - write a
module that "simulates" the board (that is, write a console script) and test
it on your computer before porting to your board.
Good luck. Please let us know if you need more help.
Tutor maillist - Tutor at python.org
To unsubscribe or change subscription options:
More information about the Tutor