ThreadLocal

2020-04-08  本文已影响0人  huashen_9126

结论: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()
上一篇 下一篇

猜你喜欢

热点阅读