Search code examples
pythonmultithreadingglobal-variables

Sharing variables across threads


already tried to solve my issue via existing posts - however, did not manage to. Thx for your help in advance.

The objective is to share a variable across threads. Please find below the code. It keeps printing '1' for the accounting variable, although I want it to print '2'. Any suggestions why?

main.py:

account = 1

import threading
import cfg
import time

if __name__ == "__main__":
    thread_cfg = threading.Thread(target=cfg.global_cfg(),args= ())
    thread_cfg.start()
    time.sleep(5)
    print(account)

cfg.py:

def global_cfg():
    global account
    account = 2
    return()

Solution

  • Globals are not shared across files.

    If we disregard locks and other synchronization primitives, just put account inside cfg.py:

    account = 1
    def global_cfg():
        global account
        account = 2
        return
    

    And inside main.py:

    import threading
    import time
    import cfg
    
    if __name__ == "__main__":
        thread_cfg = threading.Thread(target=cfg.global_cfg,args= ())
        print(cfg.account)
        thread_cfg.start()
        time.sleep(5)
        print(cfg.account)
    

    Running it:

    > py main.py
    1
    2
    

    In more advanced cases, you should use Locks, Queues and other structures, but that's out of scope.