码迷,mamicode.com
首页 > 其他好文 > 详细

threding.local

时间:2019-09-28 16:18:36      阅读:106      评论:0      收藏:0      [点我收藏+]

标签:get   imp   空间   target   int   threading   range   _id   exception   

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

示例

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()

 

threding.local

标签:get   imp   空间   target   int   threading   range   _id   exception   

原文地址:https://www.cnblogs.com/wt7018/p/11603467.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!