Python中的线程本地存储 [英] Thread local storage in Python
本文介绍了Python中的线程本地存储的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何在Python中使用线程本地存储?
How do I use thread local storage in Python?
- 什么是线程中的线程本地存储",为什么我需要它?-该线程似乎更关注共享变量时的情况.
- What is "thread local storage" in Python, and why do I need it? - This thread appears to be focused more on when variables are shared.
- Efficient way to determine whether a particular function is on the stack in Python - Alex Martelli gives a nice solution
推荐答案
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
这篇关于Python中的线程本地存储的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文