Article / 文章中心

Python编程:threading多线程之ThreadLocal

发布时间:2021-11-23 点击数:493

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

代码示例

# -*- coding: utf-8 -*-  # @File    : thread_local_demo.py # @Date    : 2018-06-11 # @Author  : Peng Shiyu  import threading  # 创建全局ThreadLocal对象 local_dict = threading.local()  def process_item():  # 获取当前线程关联的name  name = local_dict.name  print("thread: %s  name: %s"% (threading.current_thread().name, name))  def process_thread(name):  # 绑定ThreadLocal的name  local_dict.name = name  process_item()  t1 = threading.Thread(target=process_thread, args=("Tom",), name="Thread-Tom") t2 = threading.Thread(target=process_thread, args=("Jack",), name="Thread-Jack")  t1.start() t2.start()  t1.join() t2.join() """ thread: Thread-Tom  name: Tom thread: Thread-Jack  name: Jack """