python threading.local
在threading module中,有一个非常特别的local。一旦在主线程实例化了一个local,它会一直活在主线程中,并且主线程启动了子线程调用这个local实例时,它的值将会保存在相应的子线程的字典中。
from threading import local, enumerate, Thread, current_thread
local_data = local()
local_data.name = 'local_data'
class TestThread(Thread):
def run(self):
print(current_thread())
print(local_data.__dict__)
local_data.name = self.getName()
local_data.add_by_sub_thread = self.getName()
print(local_data.__dict__)
if __name__ == '__main__':
print(current_thread())
print(local_data.__dict__)
t1 = TestThread()
t1.start()
t1.join()
t2 = TestThread()
t2.start()
t2.join()
print(current_thread())
print(local_data.__dict__)
打印结果:
<_MainThread(MainThread, started 7256)>
{‘name’: ‘local_data’}
<TestThread(Thread-1, started 12408)>
{}
{‘add_by_sub_thread’: ‘Thread-1’, ‘name’: ‘Thread-1’}
<TestThread(Thread-2, started 15948)>
{}
{‘add_by_sub_thread’: ‘Thread-2’, ‘name’: ‘Thread-2’}
<_MainThread(MainThread, started 7256)>
{‘name’: ‘local_data’}