首页 > 其他 > 详细

flask 源码专题(七):threading.local和高级

时间:2020-04-05 16:43:31      阅读:64      评论:0      收藏:0      [点我收藏+]

1.python之threading.local

  • 当每个线程在执行 val.num=1 ,在内部会为此线程开辟一个空间,来存储 num=1

  • val.num,找到此线程自己的内存地址去取自己存储 num

import time
import threading

val1 = threading.local()

def task(i):
    val.num = i
    time.sleep(1)
    print(val.num)

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

2. 线程唯一标识

  get_ident

import threading
from threading import get_ident

def task():
    ident = get_ident()
    print(ident)
for i in range(20):
    t = threading.Thread(target=task)
    t.start()

3. 自定义threading.local

储存结构:

storage = {
1112:{‘x1‘:1}
1113:{‘x1‘:2}
1114:{‘x1‘:3}
1115:{‘x1‘:4}
}

import threading
class Local(object):
    def __init__(self):
        object.__setattr__(self,storage,{})

    def __setattr__(self, key, value):
        ident = threading.get_ident()
        if ident in self.storage:
            self.storage[ident][key] = value
        else:
            self.storage[ident] = {key:value}

    def __getattr__(self, item):
        ident = threading.get_ident()
        if ident not in self.storage:
            return
        return self.storage[ident].get(item)

local = Local()

def task(arg):
    local.x1 = arg
    print(local.x1)

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

4. 加强版threading.local

储存结构:

storage = {
1111:{‘x1‘:[]},
1112:{‘x1‘:[]}
1113:{‘x1‘:[]}
1114:{‘x1‘:[]}
1115:{‘x1‘:[]},
1116:{‘x1‘:[]}
}

import threading
class Local(object):
    def __init__(self):
        object.__setattr__(self,storage,{})

    def __setattr__(self, key, value):
        ident = threading.get_ident()
        if ident in self.storage:
            self.storage[ident][key].append(value)
        else:
            self.storage[ident] = {key:[value,]}

    def __getattr__(self, item):
        ident = threading.get_ident()
        if ident not in self.storage:
            return
        return self.storage[ident][item][-1]

local = Local()

def task(arg):
    local.x1 = arg
    print(local.x1)

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

 

flask 源码专题(七):threading.local和高级

原文:https://www.cnblogs.com/qiu-hua/p/12637669.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!