[Tutor] threading in python 2.7 - 2nd version

Joseph Lee joseph.lee22590 at gmail.com
Mon Jan 5 06:54:34 CET 2015


Hi,
My answers are below.

-----Original Message-----
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
To: tutor
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.

<python>

#threading problem example

import threading
import sys
import time

threads = []

exitFlag = 0

def delay(ms):
    time.sleep(1.0*ms/1000)

def threadloop():
    while not exitFlag:
        print "exitFlag value: ", exitFlag
        delay(2000)

def cleanup():
    exitFlag = 1
    print "Exit flag value: ", exitFlag
    for t in threads:
        t.join()
    sys.exit()

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
variables.
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.

</python>

Original:

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
exitFlag?

jL: See my comment and flow chart above.
_______________________________________________
Tutor maillist  -  Tutor at python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor



More information about the Tutor mailing list