[Tutor] threading in python 2.7 - 2nd version
joseph.lee22590 at gmail.com
Mon Jan 5 06:54:34 CET 2015
My answers are below.
From: Tutor [mailto:tutor-bounces+joseph.lee22590=gmail.com at python.org] On
Behalf Of Rance Hall
Sent: Sunday, January 4, 2015 9:20 PM
Subject: [Tutor] threading in python 2.7 - 2nd version
Thanks to the advice from Joseph and Alan, I hacked a quick python script
which demonstrates my problem more accurately.
Its not board specific as was my last code. This sample works the same on
my pcduino as it does on my desktop.
#threading problem example
threads = 
exitFlag = 0
while not exitFlag:
print "exitFlag value: ", exitFlag
exitFlag = 1
print "Exit flag value: ", exitFlag
for t in threads:
JL: Hmmm, can you take a look at the above code for cleanup function? If you
look at it carefully, you'll see why the program will enter infinite loop.
Specifically, take a look at the following textual chart:
Function : exitFlag : threads
main : global.exitFlag : global.threads
loop : global.exitFlag : global.threads
cleanup : cleanup.exitFlag : cleanup.threads
As you can see, something odd is going on in cleanup function: it has its
own exit flag and threads pool. If you ever need to peek a look at a
variable outside of a given function (local scope) nad mess with it, you
need to add the following at the beginning of the function in question:
Gglobal *globalVars # I used * in there to denote unknown number of
In other words, the bug had to do with scope resolution, which is very
important when threads need to access or modify global variables. That is,
just because you give the variable the same name as a global flag in a
function doesn't mean you are reading the actual global flags, which is what
the threads here were trying to do.
the thread driven loop doesn't ever see the fact that the exitFlag as
changed, based on the output to screen.
Be warned, this code gives you an infinite loop, so be sure to run it in a
terminal you can kill without impacting other work you are doing.
There are many ways to work with theads. Class definitions, etc. The
thread and threading modules.
I've tried several and get the same results.
What do I need to do to get the thread to stop based on the value of
jL: See my comment and flow chart above.
Tutor maillist - Tutor at python.org
To unsubscribe or change subscription options:
More information about the Tutor