local对象
一、local对象
1.1不使用local
# 不用local
from threading import Thread
import time
cxw = -1
def task(arg):
global cxw
cxw = arg
time.sleep(2)
print(cxw)
for i in range(10):
t = Thread(target=task, args=(i,))
t.start()
结果:9 9 9 9 9 9 9 9 9 9
1.2导入的local
from threading import Thread
from threading import local
import time
# 特殊的对象
cxw = local()
def task(arg):
# 对象.val = 1/2/3/4/5
cxw.value = arg
time.sleep(2)
print(cxw.value)
for i in range(10):
t = Thread(target=task,args=(i,))
t.start()
结果:0 2 3 4 6 5 8 7 9
1.3字典形式
from threading import get_ident, Thread
import time
storage = {}
def set(k, v):
'''
所有k都相同,根据线程的id不同来进行设置值
:param k:
:param v:
:return:
'''
ident = get_ident()
if ident in storage:
storage[ident][k] = v
else:
storage[ident] = {k: v}
def get(k):
"""
根据当前的线程id获取值
:param k:
:return:
"""
ident = get_ident()
return storage[ident][k]
def task(arg):
set('val', arg)
time.sleep(2)
v = get('val')
print(v)
for i in range(10):
t = Thread(target=task, args=(i,))
t.start()
结果:0 1 2 3 6 4 5 9 8 7
1.4面向对象的方式
from threading import get_ident, Thread
import time
class Local(object):
storage = {}
def set(self, k, v):
ident = get_ident()
if ident in Local.storage:
Local.storage[ident][k] = v
else:
Local.storage[ident] = {k: v}
def get(self, k):
ident = get_ident()
return Local.storage[ident][k]
obj = Local()
def task(arg):
obj.set('val', arg)
v = obj.get('val')
print(v)
for i in range(10):
t = Thread(target=task, args=(i,))
t.start()
结果:0 1 2 3 6 4 5 9 8 7
1.5 每个对象都有自己的storage
# try...except...根据源码实现
try:
from greenlet import getcurrent as get_ident
except Exception as e:
from threading import get_ident
from threading import Thread
# from threading import get_ident,Thread
import time
class Local(object):
def __init__(self):
object.__setattr__(self, 'storage', {}) # 使用父类方式添加,否则__getattr__会出现递归
# self.storage={}
# storage={}
def __setattr__(self, k, v):
ident = get_ident()
if ident in self.storage: # self.storage会到__getattr__中找,在__getattr__中没有没有也要找,自己调用自己,从而就导致了递归,疑惑:在__init__中已经产生创建了,怎们还会产生递归循环
self.storage[ident][k] = v
else:
self.storage[ident] = {k: v}
def __getattr__(self, k):
ident = get_ident()
return self.storage[ident][k]
obj = Local()
obj1 = Local()
def task(arg):
obj.val = arg
obj.xxx = arg
print(obj.val)
for i in range(10):
t = Thread(target=task, args=(i,))
t.start()
结果:0 1 2 3 6 4 5 9 8 7
在当下的阶段,必将由程序员来主导,甚至比以往更甚。