美文网首页
Python:23.ThreadLocal

Python:23.ThreadLocal

作者: 许瘦子来世 | 来源:发表于2018-07-12 16:18 被阅读24次
# ThreadLocal
'''
1. 一个ThreadLocal变量虽然是全局变量,但每个线程都只能读写自己线程上的独立副本,互不干扰。
2. 解决了参数在一个线程中各个函数之间互相传递的问题
'''

import threading

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

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

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

t1 = threading.Thread(target=process_thread, args=('Alice',), name='Thread-A')
t2 = threading.Thread(target=process_thread, args=('Bob',), name='Thread-B')
t1.start()
t2.start()
t1.join()
t2.join()

相关文章

网友评论

      本文标题:Python:23.ThreadLocal

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