示例
import time
from threading import local, Thread
num = 0
def task(arg):
global num
num = arg
time.sleep(2)
print(num)
for i in range(10):
t = Thread(target=task, args=(i,))
t.start()
- 使用线程每次给变量 + 1.
- 这样会使值相同, 都是最后一次改变的值.
使用threading.local避免这样的情况
import time
from threading import local, Thread
# 实例化一个local对象
num = local()
def task(arg):
num = arg
time.sleep(2)
print(num)
for i in range(10):
t = Thread(target=task, args=(i,))
t.start()
- 这样相当于每个线程过来的时候给它开辟一个空间. 存取它们的值.
自定义Local
基于函数
import time
from threading import get_ident, Thread
storage = {}
def set(k, v):
ident = get_ident()
if ident in storage:
storage[ident][k] = v
else:
storage[ident] = {k: v}
def get(k):
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()
基于面向对象
import time
from threading import get_ident, Thread
class Local(object):
def __init__(self):
object.__setattr__(self, 'storage', {})
def __setattr__(self, k, v):
ident = get_ident()
if ident in self.storage:
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()
def task(arg):
obj.val = arg
print(obj.val)
for i in range(10):
t = Thread(target=task, args=(i,))
t.start()