美文网首页
ThreadLocal

ThreadLocal

作者: huashen_9126 | 来源:发表于2020-04-08 23:07 被阅读0次

结论:ThreadLocal解决了参数在一个线程中各个函数之间互相传递的问题,一个ThreadLocal变量虽然是全局变量,但每个线程都只能读写自己线程的独立副本,互不干扰

import threading

local_school = threading.local()

def process_student():
    std = local_school.student
    print(f'Hello {std} in {threading.current_thread().name}')

def process_thread(name):
    local_school.student = name
    process_student()

t1 = threading.Thread(target=process_thread, args=('bob',), name='Thead-A')
t2 = threading.Thread(target=process_thread, args=('lily',), name='Thead-B')
t1.start()
t2.start()
t1.join()
t2.join()

相关文章

网友评论

      本文标题:ThreadLocal

      本文链接:https://www.haomeiwen.com/subject/mxdfmhtx.html