Python threading.local() 在线程中不工作 class
Python threading.local() not working in Thread class
在Python3.6 中,我使用threading.local() 来存储线程的一些状态。
这是一个简单的例子来解释我的问题:
import threading
class Test(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
self.local = threading.local()
self.local.test = 123
def run(self):
print(self.local.test)
当我开始这个话题时:
t = Test()
t.start()
Python 给我一个错误:
AttributeError: '_thread._local' object has no attribute 'test'
似乎 test 属性无法访问 __init__ 函数范围之外,因为我可以打印值在 __init__ 函数中,在局部设置属性后 test=123.
是否有必要在 Thread 子类中使用 threading.local 对象?我认为 Thread 实例的实例属性可以保证属性线程安全。
无论如何,为什么 threading.local 对象在实例函数之间没有按预期工作?
当您构建线程时,您使用的是不同的线程。当您在线程上执行 运行 方法时,您正在启动一个新线程。该线程还没有设置线程局部变量。这就是为什么您没有在构造线程对象的线程上设置属性,而不是在线程 运行ning 对象上设置属性。
如https://docs.python.org/3.6/library/threading.html#thread-local-data所述:
The instance’s values will be different for separate threads.
Test.__init__
在调用者的线程中执行(例如 t = Test()
执行的线程)。是的,这是 创建 thread-local 存储 (TLS) 的好地方。
但是当t.run
执行时,它会有完全不同的内容——只能在线程t
中访问的内容。
当您需要在当前线程范围内共享数据时,TLS 非常有用。它就像函数内的一个局部变量——但对于线程而言。当线程完成执行时——TLS 消失。
用于 inter-thread 通信 Futures can be a good choice. Some others are Conditional variables, events, etc. See threading 文档页面。
在Python3.6 中,我使用threading.local() 来存储线程的一些状态。 这是一个简单的例子来解释我的问题:
import threading
class Test(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
self.local = threading.local()
self.local.test = 123
def run(self):
print(self.local.test)
当我开始这个话题时:
t = Test()
t.start()
Python 给我一个错误:
AttributeError: '_thread._local' object has no attribute 'test'
似乎 test 属性无法访问 __init__ 函数范围之外,因为我可以打印值在 __init__ 函数中,在局部设置属性后 test=123.
是否有必要在 Thread 子类中使用 threading.local 对象?我认为 Thread 实例的实例属性可以保证属性线程安全。
无论如何,为什么 threading.local 对象在实例函数之间没有按预期工作?
当您构建线程时,您使用的是不同的线程。当您在线程上执行 运行 方法时,您正在启动一个新线程。该线程还没有设置线程局部变量。这就是为什么您没有在构造线程对象的线程上设置属性,而不是在线程 运行ning 对象上设置属性。
如https://docs.python.org/3.6/library/threading.html#thread-local-data所述:
The instance’s values will be different for separate threads.
Test.__init__
在调用者的线程中执行(例如 t = Test()
执行的线程)。是的,这是 创建 thread-local 存储 (TLS) 的好地方。
但是当t.run
执行时,它会有完全不同的内容——只能在线程t
中访问的内容。
当您需要在当前线程范围内共享数据时,TLS 非常有用。它就像函数内的一个局部变量——但对于线程而言。当线程完成执行时——TLS 消失。
用于 inter-thread 通信 Futures can be a good choice. Some others are Conditional variables, events, etc. See threading 文档页面。