threading.local()的实例化机制
threading.local() 的实例化机制
-
threading.local() 是全局实例化一次的:
-
它在模块/类/函数级别(通常在 __init__ 或全局作用域)创建一个单一的 local 对象实例(类型为 _thread._local)。
-
这个对象本身是共享的(所有线程看到同一个 ID),但内部实现了一个线程本地存储(TLS)代理:当每个线程首次访问它时,会动态为该线程创建一个独立的“本地字典”(基于线程 ID 隔离),后续访问复用这个本地字典。
-
-
示例
#! /usr/bin/env python # -*- coding: utf-8 -*- import time import threading import concurrent.futures local_storage = threading.local() # 全局实例化,然后每个线程中使用或存储时,使用的是线程键 def task_local(task_id): thread = threading.current_thread() if not hasattr(local_storage, 'counter_local'): local_storage.counter_local = 0 print(f"{thread.name} 新线程:counter_local 初始化为 0") else: local_storage.counter_local += 1 print(f"{thread.name} 复用线程:counter_local 现在是 {local_storage.counter_local}") time.sleep(0.1) return f"local 方法 - 任务 {task_id} 完成,counter_local={local_storage.counter_local}" with concurrent.futures.ThreadPoolExecutor(max_workers=2) as executor: futures_local = [executor.submit(task_local, i) for i in range(4)] for future in concurrent.futures.as_completed(futures_local): print(future.result())
-
输出
ThreadPoolExecutor-0_0 新线程:counter_local 初始化为 0 ThreadPoolExecutor-0_1 新线程:counter_local 初始化为 0 ThreadPoolExecutor-0_0 复用线程:counter_local 现在是 1 ThreadPoolExecutor-0_1 复用线程:counter_local 现在是 1 local 方法 - 任务 0 完成,counter_local=0 local 方法 - 任务 1 完成,counter_local=0 local 方法 - 任务 3 完成,counter_local=1 local 方法 - 任务 2 完成,counter_local=1

浙公网安备 33010602011771号