threding.local

本文深入探讨了线程局部存储(Thread Local Storage)的概念,通过Python示例代码展示了如何为每个线程分配独立的内存空间,避免了全局变量的线程间冲突。同时,对比了不同实现方式的优劣,包括使用threading模块的本地方法和greenlet模块的改进方案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

作用:为每一个线程开辟一个独立的内存空间

示例

from threading import Thread, local
import time

obj = local()


def test(i):
    obj.xx = i
    time.sleep(2)
    print(obj.xx, i)


for i in range(10):
    t = Thread(target=test, args=(i, ))
    t.start()

实现原理

from threading import Thread
import threading
import time

#
dic = {}


def test(i):
    index = threading.get_ident()
    if index in dic:
        dic[index]['xx'] = i
    else:
        dic[index] = {'xx': i}
    time.sleep(1)
    print(dic[index]['xx'], i)


for i in range(10):
    t = Thread(target=test, args=(i, ))
    t.start()

改良

import threading
import time
import greenlet

try:
    get_ident = greenlet.getcurrent
except Exception as e:
    get_ident = threading.get_ident


class Local:
    dic = {}

    def __getattr__(self, item):
        index = get_ident()
        if index in self.dic:
            return self.dic[index][item]
        else:
            return None

    def __setattr__(self, key, value):
        index = get_ident()
        if index in self.dic:
            self.dic[index][key] = value
        else:
            self.dic[index] = {key: value}


obj = Local()


def test(a):
    obj.xx = a
    time.sleep(2)
    print(obj.xx, a)


for i in range(10):
    t = threading.Thread(target=test, args=(i, ))
    t.start()

 

转载于:https://www.cnblogs.com/wt7018/p/11603467.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值