threading.local and senior

threading.local Features:

① open space for each thread, allowing you to access the value (a fixed value based on the thread ID)

②flask no threading.local, but the idea of ​​context management flask is for reference threading.local.

③ thread before closing value remains the same, thread closed after the value is cleared.

Ordinary multithreading

import time
import threading


class Foo(object):
        def __init__(self):
                self.num = 0

val2 = Foo()

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

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

结果:
3
3
3
3
4个值全一样

 

threading.local multithreading

Import Time
 Import Threading
 # when each thread execution val1.xx = 1, the internal thread will open up a space for this purpose, to store 1 = xx 
# val1.xx, find this thread its own memory address to pick up their own store xx 
val1 = threading.local () 

DEF Task (I): 
        val1.num = I 
        the time.sleep ( . 1 )
         Print (val1.num) 

for I in Range (. 4 ): 
        T = of the threading.Thread (target = Task, args = ( I,)) 
        t.start 

output: 
0
 . 1 
2 
. 3 
different four results

 

Custom threading.local

Import Threading
 "" " 
Storage = {# custom maintain such a dictionary 
1111: { 'X1': 0}, 
1112: { 'X1':. 1} 
1113: { 'X1': 2} 
1114: { 'X1 ':. 3} 
1115: {' X1 ':. 4} 
} 
"" " 
class the Local (Object):
         DEF  the __init__ (Self): 
                Object. __setattr__ (Self, ' Storage ' , {}) 

        DEF  __setattr__ (Self, Key, value ): 
                ident = threading.get_ident ()      # this is the thread the above mentioned id 
                IF ident in self.storage:
                        self.storage[ident][key] = value
                else:
                        self.storage[ident] = {key:value}

        def __getattr__(self, item):
                ident = threading.get_ident()     #这个就是线程id
                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()

输出:
0
1
2
3
4

The output will be a different value based on your different thread ID

 Enhanced Custom threading.local (flask context management so)

 

The original maintenance is to be a dictionary or dictionaries:
 "" " 
Storage = { 
1111: { 'X1': 0}, 
1112: { 'X1':. 1} 
1113: { 'X1': 2} 
1114: { 'X1' :}. 3 
1115: { 'X1':. 4} 
} 
"" " 
enhanced maintenance is to add a list of the dictionary is a dictionary: 
" "" 
Storage = { 
1111: { 'X1': [0,1]}, 
1112 : { 'X1': [0,1,2]} 
1113: { 'X1': [0,1,3]} 
1114: { 'X1': [0,1,5]} 
1115: { 'X1' : [0,1,6]} 
} 
"" " 
the list maintained as to stack (append is added thereto, if the value is to use [ -1 ], if the value is taken away by pop) is used, LIFO 

Import Threading
 "" " 
Storage = { 
1111: { 'X1': []}, 
1112: { 'x1':[]}
1113:{'x1':[]}
1114:{'x1':[]}
1115:{'x1':[]},
1116:{'x1':[]}
}
"""
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()
输出:
0
1
2
3
4

 

Guess you like

Origin www.cnblogs.com/shengjunqiye/p/11923729.html