【Python】多线程之线程本地数据

创建一个线程本地对象

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
......
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值