Threading.local

在多线程环境下,每个线程都有自己的数据。一个线程使用自己的局部变量比使用全局变量好,因为局部变量只有线程自己能看见,不会影响其他线程,而全局变量的修改必须加锁。

Threading.local可以创建一个对象,每个线程都可以对他读写属性,但不会互相影响

import threading
import time
# 创建全局ThreadLocal对象:
class A:
    pass
# local_school = A()
local_school = threading.local()

def process_student():
    print('Hello, %s (in %s)' % (local_school.student, threading.current_thread().name))

def process_thread(name):
    # 绑定ThreadLocal的student:

    local_school.student = name
    time.sleep(2)
    process_student()
a = []
for i in range(20):
    a.append(threading.Thread(target= process_thread, args=(str(i),), name=str(i)))

for i in a:
    i.start()

通过字典以及面向对象中的魔法方法来自己实现一个

import time
from threading import get_ident,Thread
class PPP:
    def __init__(self):
        object.__setattr__(self,"storage", {})
    def __setattr__(self, key, value):
        if get_ident() in self.storage:
            self.storage[get_ident()][key]=value
        else:
            self.storage[get_ident()] ={key: value}
    def __getattr__(self, item):
        return  self.storage[get_ident()][item]

p =PPP()
def task(arg):
    p.a = arg
    time.sleep(2)
    print(p.a)


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

  

posted @ 2018-04-23 19:52  瓜田月夜  阅读(326)  评论(0编辑  收藏  举报