Thread local storage in Python

后端 未结 5 1526
-上瘾入骨i
-上瘾入骨i 2020-11-27 10:33

How do I use thread local storage in Python?

Related

  • What is “thread local storage” in Python, and why do I need it? - This thread appears to be focuse
5条回答
  •  温柔的废话
    2020-11-27 11:22

    My way of doing a thread local storage across modules / files. The following has been tested in Python 3.5 -

    import threading
    from threading import current_thread
    
    # fileA.py 
    def functionOne:
        thread = Thread(target = fileB.functionTwo)
        thread.start()
    
    #fileB.py
    def functionTwo():
        currentThread = threading.current_thread()
        dictionary = currentThread.__dict__
        dictionary["localVar1"] = "store here"   #Thread local Storage
        fileC.function3()
    
    #fileC.py
    def function3():
        currentThread = threading.current_thread()
        dictionary = currentThread.__dict__
        print (dictionary["localVar1"])           #Access thread local Storage
    

    In fileA, I start a thread which has a target function in another module/file.

    In fileB, I set a local variable I want in that thread.

    In fileC, I access the thread local variable of the current thread.

    Additionally, just print 'dictionary' variable so that you can see the default values available, like kwargs, args, etc.

提交回复
热议问题