每天学点Python:使用全局ThreadLocal对象传递线程中的变量

每天学点Python

多线程处理函数带来的问题是,数据传递很麻烦,因此官方提供一种全局ThreadLocal对象,各层函数都可以共享线程中的变量。
当然若处理比较复杂,需要传递的参数比较多,还是建议参考我分享的Python多线程中的线程类,ThreadLocal使用非常简单,可以绑定共享各种类型的变量,使用方式如下:


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=({'1', '2'},), name='Thread-A')
t2 = threading.Thread(target=process_thread, args=('Bob',), name='Thread-B')
t1.start()
t2.start()
t1.join()
t2.join()

以上分别传递和共享set和str类型,需要的朋友们可以参考。

每天学点Python,一天掌握一个知识点,我们一起进步吧!!

发布了127 篇原创文章 · 获赞 10 · 访问量 24万+

猜你喜欢

转载自blog.csdn.net/u012599545/article/details/103019899