Discuss / Python / ThreadLocal

ThreadLocal

Topic source

Mr_RightMen

#1 Created at ... [Delete] [Delete and Lock User]
# ThreadLocal
# 在多线程环境下,每个线程都有自己的数据。一个线程使用自己的局部变量比使用全局变量好,因为局部变量只有线程自己能看见,不会影响其他线程,而全局变量必须加锁。
# 但是局部变量也有问题,就是在函数调用的时候,传递起来特别麻烦。
import os,time,random,subprocess,threading

class Student(object):
    def __init__(self,name):
        self.name = name

def do_task_1(ist):
    do_subtask_1(ist)

def do_subtask_1(ist):
    print('Hello,{0} (in {1})'.format(ist.name,threading.current_thread().name))

def process_student(name):
    std = Student(name)
    # std是局部变量,但是每个函数都要用它,因此必须传进去:
    do_task_1(std)

t1 = threading.Thread(target=process_student,args=('Alice',))
t2 = threading.Thread(target=process_student,args=('Bob',))
t1.start()
t2.start()
t1.join()
t2.join()

# process_student('Alice') --> do_task_1('Alice') --> do_subtask_1('Alice') -- > print
# 每个函数一层一层的调用都这么传肯定不行,用全局变量也不行,因为每个线程处理不同的Student对象,不能共享

# 用全局dict存放所有Student对象,然后以thread自身作为key获取当前线程对应的student对象也行
import os,multiprocessing,time,random,subprocess,threading

class Student(object):
    def __init__(self,name):
        self.name = name

global_dict = {}

def std_thread(name):
    std = Student(name)
    # 把std放到全局变量global_dict中:
    global_dict[threading.current_thread()] = std
    do_task_1()

def do_task_1():
    # 不传入std,而是根据当前线程查找:
    std = global_dict[threading.current_thread()]
    print('Hello,{0} (in {1})'.format(std.name,threading.current_thread().name))



t1 = threading.Thread(target=std_thread,args=('Alice',))
t2 = threading.Thread(target=std_thread,args=('Bob',))
t1.start()
t2.start()
t1.join()
t2.join()


# ThreadLocal方式
import threading

# 创建全局threadLocal对象
local_school = threading.local()

def process_student():
    # 获取当前线程关联的student
    std = local_school.student
    print('Hello, {0} (in {1})'.format(std,threading.current_thread().name))

def process_thread(name):
    # 绑定ThreadLocal的student
    local_school.student = name
    process_student()

t1 = threading.Thread(target=std_thread,args=('Alice',))
t2 = threading.Thread(target=std_thread,args=('Bob',))
t1.start()
t2.start()
t1.join()
t2.join()

  • 1

Reply