what thread-synch mech to use for clean exit from a thread

Gildor Oronar gildororonar at mail-on.us
Mon Jul 15 04:27:45 CEST 2013


A currency exchange thread updates exchange rate once a minute. If the 
thread faield to update currency rate for 5 hours, it should inform 
main() for a clean exit. This has to be done gracefully, because main() 
could be doing something delicate.

I, a newbie, read all the thread sync tool, and wasn't sure which one to 
use. In fact I am not sure if there is a need of thread sync, because 
there is no racing cond. I thought of this naive way:

class CurrencyExchange():
    def __init__(in_case_callback):
       this.callback = in_case_callback
    def __run__():
       while time.time() - self.rate_timestamp < 5*3600:
          ... # update exchange rate
          if success:
             self.rate_timestamp == time.time()
          time.sleep(60)
       this.callback() # rate not updated 5 hours, a crisis

def main():
    def callback()
       Go_On = False

    agio = CurrencyExchange(in_case = callback)
    agio.start()

    Go_On = True
    while Go_On:
       do_something_delicate(rate_supplied_by=agio)

As you can see, if there is no update of currency rate for 5 hours, the 
CurrencyExchange object calls the callback, which prevents main() from 
doing the next delicate_thing, but do not interrupt the current 
delicate_thing.

This seems OK, but doesn't look pythonic -- replacing callback() with a 
lambda doesn't help much, it still look naive. What is the professional 
way in this case?

Thanks in advance!



More information about the Python-list mailing list