[Tutor] threading in python2.7

Rance Hall ranceh at gmail.com
Fri Jan 2 21:17:05 CET 2015


I bought myself a pcduino 3 nano development board for Christmas and
started picking up python again after a long forced hiatus.  The board runs
Ubuntu Precise

Working with development boards has me navigating the inner working of
python threading and I find myself at a loss.

My current project is a simulated emergency vehicle warning system
(otherwise known as a police siren)

I started my project by writing the lighting and the sound portions of the
program separately and tweaking them till I got each part working as
desired.

Now to get them to start simultaneously and exit cleanly.

I started with some basic python like this:

<pseudo python>

import needed stuff

global variable declarations

def setup_hardware():
     do stuff here to setup hardware and gpio sytem

def lights():
    control the red and blue LEDs to simulate warning lights

def sound():
     control the sound to simulate a warning siren

def cleanup():
     exit cleanly and cleanup

def main():
     setup()
     try:
         # individually starting either lights or sound works as expected
     except:
         # catch keyboard interrupt and call cleanup

</pseudo python>

I've read many threading tutorials from the old thread module to the new
threading module and I've found several different ways of starting both
lights and sound in their own threads.

The issue I have is exiting the program.

All of the tutorials suggest having a global variable to indicate when to
exit the threads.

so I used a global variable called exitFlag and begin the program with it
set to 0

Each of the lights and sound functions are placed in a "while not
exitFlag:" loop

I think I'm running into some variable scoping issues related to threads,
but I'm not sure exactly.

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?

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.

Thanks all for your help.


More information about the Tutor mailing list