创建一个线程本地对象
import threading
# 创建线程本地对象
current_thread_data = threading.local()
# 为线程本地对象添加属性
current_thread_data.color = "blue"
# 直接操作线程本地对象的属性字典
current_thread_data.__dict__.setdefault("widgets",[])
# 查看本地线程的数据字典
print(current_thread_data.__dict__)
输出:
{'color': 'blue', 'widgets': []}
访问线程本地对象所有线程的数据
import threading
log = []
def f():
mydata.number = 1
# 记录当前线程的数据
log.append(mydata.number)
log.append(mydata.__dict__)
mydata = threading.local()
thread = threading.Thread(target=f)
thread.start()
thread.join()
print(log)
输出:
[1, {'number': 1}]
定制一个线程本地对象
import threading
def f():
print(mydata.color)
print(mydata.number)
mydata.color = "green"
print(mydata.__dict__)
class MyLocal(threading.local):
# 定义线程共享属性 子类中定义的类属性可以被所有线程共享
number = 1
def __init__(self, /, **kw):
# 定义所有本地线程对象的默认值属性
self.__dict__.update(kw)
def square(self):
return self.number ** 2
mydata = MyLocal(color="red")
thread = threading.Thread(target=f)
print(mydata.color)
print(mydata.number)
thread.start()
thread.join()
print(mydata.__dict__)
输出:
red
1
red
1
{'color': 'green'}
{'color': 'red'}
例子
import threading
import time
def task1():
current_thread_data.name = "task1"
while True:
time.sleep(0.5)
print(threading.current_thread() , current_thread_data.name)
def task2():
current_thread_data.name = "task2"
while True:
time.sleep(1)
print(threading.current_thread() , current_thread_data.name)
if __name__ == '__main__':
current_thread_data = threading.local()
threading.Thread(target=task1).start()
threading.Thread(target=task2).start()
输出:
<Thread(Thread-1, started 23808)> task1
<Thread(Thread-2, started 25580)> task2
<Thread(Thread-1, started 23808)> task1
<Thread(Thread-1, started 23808)> task1
<Thread(Thread-2, started 25580)> task2
<Thread(Thread-1, started 23808)> task1
<Thread(Thread-1, started 23808)> task1
<Thread(Thread-2, started 25580)> task2
<Thread(Thread-1, started 23808)> task1
<Thread(Thread-1, started 23808)> task1
......