[Tutor] threading in python 2.7 - 2nd version

Rance Hall ranceh at gmail.com
Mon Jan 5 20:00:45 CET 2015


Cameron:

This was the exact issue, and I had initially suspected as much, but had no
idea how to fix it.  I had tried to use the global variable directive, but
as it turned out I had misused it.

Anyway, everything is working as it should.

Thanks

Rance

On Mon, Jan 5, 2015 at 12:39 AM, Cameron Simpson <cs at zip.com.au> wrote:

> On 04Jan2015 23:19, Rance Hall <ranceh at gmail.com> wrote:
>
>> 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. [...]
>>
>> [...]
>> exitFlag = 0
>>
>
> Ok.
>
>  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()
>>
>
> These two hold your issue.
>
> threadloop() _does_ consult the global "exitFlag". But only because you
> never assign to it in this function. So when you consult the name
> "exitFlag", it looks for a local variable and does not find one, so it
> looks in the global scope and finds it there.
>
> cleanup() uses exitFlag as a _local_ variable (like most variables in
> python).  This is because it assigns to it. Python will always use a local
> variable for something you assign to unless you tell it not to; that (by
> default) keeps the effects of a function within the function. Because of
> this, cleanup does not affect the global variable.
>
> Here, it would be best to add the line:
>
>    global exitFlag
>
> at the top of _both_ functions, to be clear that you are accessing the
> global in both cases. So:
>
>  def threadloop():
>      global exitFlag
>      while not exitFlag:
>          print "exitFlag value: ", exitFlag
>          delay(2000)
>   def cleanup():
>      global exitFlag
>      exitFlag = 1
>      print "Exit flag value: ", exitFlag
>      for t in threads:
>          t.join()
>      sys.exit()
>
> Cheers,
> Cameron Simpson <cs at zip.com.au>
>
> Out of memory.
> We wish to hold the whole sky,
> But we never will.
> - Haiku Error Messages http://www.salonmagazine.com/
> 21st/chal/1998/02/10chal2.html
>
> _______________________________________________
> 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