[Tutor] threading in python 2.7 - 2nd version
Rance Hall
ranceh at gmail.com
Mon Jan 5 06:19:33 CET 2015
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()
def main():
try:
my_thread = threading.Thread( target = threadloop, args = () )
my_thread.start()
threads.append(my_thread)
delay(20)
keypress = raw_input("Press a key and hit Enter to exit\n")
cleanup()
except KeyboardInterrupt:
cleanup()
main()
</python>
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?
More information about the Tutor
mailing list