Discuss / Python / ThreadLoca解决多线程数据使用问题

ThreadLoca解决多线程数据使用问题

Topic source

import threading

#创建全局ThreadLocal对象

local_school = threading.local()

#处理学生信息函数

def process_student():

    #获取当前线程关联的student值

    std = local_school.student

    #打印学生信息和线程名

    print('Heloo, %s (in %s)' % (std,threading.current_thread().name))

#绑定学生信息并调用process_student函数

def process_thread(name):

    local_school.student = name

    process_student()

#创建2个线程对象测试

t1 = threading.Thread(target=process_thread,args=('Alice',),name='Tread-A')

t2 = threading.Thread(target=process_thread,args=('Bob',),name='Tread-B')

t1.start()

t2.start()

t1.join()

t2.join()


  • 1

Reply