Thread local storage in Python

后端 未结 5 1539
-上瘾入骨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:14

    As noted in the question, Alex Martelli gives a solution here. This function allows us to use a factory function to generate a default value for each thread.

    #Code originally posted by Alex Martelli
    #Modified to use standard Python variable name conventions
    import threading
    threadlocal = threading.local()    
    
    def threadlocal_var(varname, factory, *args, **kwargs):
      v = getattr(threadlocal, varname, None)
      if v is None:
        v = factory(*args, **kwargs)
        setattr(threadlocal, varname, v)
      return v
    

提交回复
热议问题