python - 如何清除 Python threading.local 对象?

标签 python multithreading

如何清除 Python 的 threading.local() 实例的所有属性?

最佳答案

你可以清除它的底层__dict__:

>>> l = threading.local()
>>> l
<thread._local object at 0x7fe8d5af5fb0>
>>> l.ok = "yes"
>>> l.__dict__
{'ok': 'yes'}
>>> l.__dict__.clear()
>>> l.__dict__
{}
>>> l.ok
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'thread._local' object has no attribute 'ok'

_threading_local 模块文档中,直接访问 __dict__ 被明确称为与 local 对象交互的有效方式:

Thread-local objects support the management of thread-local data. If you have data that you want to be local to a thread, simply create a thread-local object and use its attributes:

  >>> mydata = local()
  >>> mydata.number = 42
  >>> mydata.number
  42

You can also access the local-object's dictionary:

  >>> mydata.__dict__
  {'number': 42}
  >>> mydata.__dict__.setdefault('widgets', [])
  []
  >>> mydata.widgets
  []

关于python - 如何清除 Python threading.local 对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25693508/

相关文章:

c++ - boost::lockfree:queue 中的内存排序

python - 如何为 Python 属性实现 __iadd__

python - 将数组转换为 python 列表列表

python - 如何在撰写文件中正确定义服务

python - 如何以特定方式将一个小矩阵沿对角线添加到一个较大的矩阵中?

java - 当对象持有对正在运行的线程的引用时,该对象是否有资格进行垃圾回收?

Python 点击​​ : Having the group execute code AFTER a command

c# - Thread.CurrentThread.Join() 什么时候有意义?

c++ - boost::condition::timed_wait 的使用示例

ios - 处理核心数据中的大量删除/插入