What if/ should I use threading to update global variables.[pythonic way]
Question: I have a function to update a global/class variable. So, What should care
after regularly invoke such function as subthread?(in asynchronous way)

Or, any suggestions to avoid using this pattern? (the pathonic way)

    
    
    import time
    import threading
    
    # through global variable or class variable
    _a = 123
    
    
    def update_a():        # may be called more than once
        "slow updating process"
        time.sleep(3)
        global _a
        _a += 10
        return
    
    if __name__ == '__main__':
        print(_a)
        th = threading.Thread(target=update_a)
        th.setDaemon(True)
        th.start()
        print(_a)
        # updating aynchrounously
        time.sleep(5)
        print(_a)
    


Answer: First of all, threads are a thing to avoid in Python altogether, but if you
really want to, I'd do it like this. First, create a thread-safe object with a
[lock](http://docs.python.org/2/library/threading.html#lock-objects):

    
    
    class ThreadSafeValue(object):
        def __init__(self, init):
            self._value = init
            self._lock = threading.Lock()
    
        def atomic_update(self, func):
            with self._lock:
                self._value = func(self._value)
    
        @property
        def value(self):
            return self._value
    

then I'd pass that to the thread target function:

    
    
    def update(val):
        time.sleep(3)
        val.atomic_update(lambda v: v + 10)
    
    def main():
        a = ThreadSaveValue(123)
        print a.value
        th = threading.Thread(target=update, args=(a,))
        th.daemon = True
        th.start()
        print a.value
        th.join()
        print a.value
    
    if __name__ == '__main__':
        main()
    

That way you will avoid global variables and ensure the thread-safety.

