Threading.local的作用 为每个线程创建一个独立的空间,使得线程对自己的空间中的数据进行操作(数据隔离) 代码实现如下 import threading from threading import local import time obj = local() def tas
Threading.local的作用
为每个线程创建一个独立的空间,使得线程对自己的空间中的数据进行操作(数据隔离)
代码实现如下
from threading import local
import time
obj = local()
def task(i):
obj.xxxxx = i
time.sleep(2)
print(obj.xxxxx,i)
for i in range(10):
t = threading.Thread(target=task,args=(i,))
t.start()
如何获取一个线程的唯一标记?
可利用threading.get_ident()
import threadingdef task(i):
print(threading.get_ident(),i)
for i in range(10):
t = threading.Thread(target=task,args=(i,))
t.start()
运行结果
10060 02572 1
4900 2
18088 3
10352 4
1372 5
17796 6
2476 7
14596 8
17488 9
根据字典自定义一个类似于threading.local功能?并可为协程创建独立的空间
import timeimport threading
import greenlet
DIC = {}
def task(i):
# ident = threading.get_ident()
ident = greenlet.getcurrent() #获得协程标记
if ident in DIC:
DIC[ident]['xxxxx'] = i
else:
DIC[ident] = {'xxxxx':i }
time.sleep(2)
print(DIC[ident]['xxxxx'],i)
for i in range(10):
t = threading.Thread(target=task,args=(i,))
t.start()
将上述代码进行优化,封装到对象中,方便调用
import timeimport threading
try:
import greenlet
get_ident = greenlet.getcurrent
except Exception as e:
get_ident = threading.get_ident
class Local(object):
DIC = {}
def __getattr__(self, item):
ident = get_ident()
if ident in self.DIC:
return self.DIC[ident].get(item)
return None
def __setattr__(self, key, value):
ident = get_ident()
if ident in self.DIC:
self.DIC[ident][key] = value
else:
self.DIC[ident] = {key:value}
obj = Local()
def task(i):
obj.xxxxx = i
time.sleep(2)
print(obj.xxxxx,i)
for i in range(10):
t = threading.Thread(target=task,args=(i,))
t.start()