Python多线程共享数据主要依靠全局变量加锁、queue.Queue、threading.local和concurrent.futures。1. 全局变量配合threading.Lock确保原子操作,避免竞态;2. queue.Queue实现线程安全的生产者-消费者通信;3. threading.local为线程提供独立数据副本,防止交叉污染;4. concurrent.futures通过Future对象简化任务提交与结果获取。根据场景选择:状态共享用Lock,解耦通信用Queue,上下文隔离用local,结果汇总用futures。

Python多线程之间共享数据主要依赖于全局变量、queue.Queue、线程局部存储(threading.local)以及使用锁机制保障数据安全。由于GIL(全局解释器锁)的存在,Python线程虽然不能真正并行执行CPU密集任务,但在IO密集场景下仍广泛使用多线程,因此数据共享与安全尤为重要。
1. 全局变量 + 锁(Lock)实现安全共享
多个线程可以访问同一个全局变量,但直接修改会导致数据竞争。使用 threading.Lock 可避免冲突。
- 通过 acquire() 和 release() 控制对共享资源的独占访问
- 推荐使用上下文管理器(with语句)自动加锁释放
示例代码:
import threading <p>counter = 0 lock = threading.Lock()</p><p>def increment(): global counter for _ in range(100000): with lock: counter += 1</p><p>threads = [threading.Thread(target=increment) for _ in range(5)] for t in threads: t.start() for t in threads: t.join()</p><p>print(counter) # 输出:500000,数据正确</p><p><span>立即学习</span>“<a href="https://pan.quark.cn/s/00968c3c2c15" style="text-decoration: underline !important; color: blue; font-weight: bolder;" rel="nofollow" target="_blank">Python免费学习笔记(深入)</a>”;</p>
2. 使用 queue.Queue 进行线程间通信
queue.Queue 是线程安全的队列,非常适合生产者-消费者模型,无需手动加锁。
- put() 和 get() 方法天然支持线程安全
- 可设置最大容量,避免内存溢出
- 支持阻塞操作,便于控制流程同步
示例:生产者和消费者共享数据
import threading
import queue
import time
<p>q = queue.Queue(maxsize=5)</p><div class="aritcle_card flexRow">
<div class="artcardd flexRow">
<a class="aritcle_card_img" href="/ai/2668" title="纳米漫剧流水线"><img
src="https://img.php.cn/upload/ai_manual/001/246/273/176982958961660.png" alt="纳米漫剧流水线" onerror="this.onerror='';this.src='/static/lhimages/moren/morentu.png'" ></a>
<div class="aritcle_card_info flexColumn">
<a href="/ai/2668" title="纳米漫剧流水线">纳米漫剧流水线</a>
<p>360推出的国内首个工业级AI漫剧生产平台</p>
</div>
<a href="/ai/2668" title="纳米漫剧流水线" class="aritcle_card_btn flexRow flexcenter"><b></b><span>下载</span> </a>
</div>
</div><p>def producer():
for i in range(10):
q.put(f"data-{i}")
print(f"Produced: data-{i}")
time.sleep(0.1)</p><p>def consumer():
while True:
try:
data = q.get(timeout=2)
print(f"Consumed: {data}")
q.task_done()
except queue.Empty:
break</p><p>t1 = threading.Thread(target=producer)
t2 = threading.Thread(target=consumer)
t1.start(); t2.start()
t1.join(); t2.join()</p>3. 使用 threading.local 实现线程私有数据
有时需要每个线程拥有独立的数据副本,避免交叉污染。threading.local 提供线程本地存储。
- 每个线程对 local 对象的修改互不影响
- 适合保存数据库连接、用户会话等上下文信息
示例:
import threading
<p>local_data = threading.local()</p><p>def process(name):
local_data.name = name
print(f"Thread {threading.current_thread().name}: {local_data.name}")</p><p>t1 = threading.Thread(target=process, args=("Alice",))
t2 = threading.Thread(target=process, args=("Bob",))
t1.start(); t2.start()
t1.join(); t2.join()</p>4. 使用 concurrent.futures 管理线程与结果传递
concurrent.futures 提供高级接口,可通过 Future 对象安全获取线程返回值。
- submit() 提交任务,返回 Future 对象
- result() 获取执行结果,自动处理异常
- 适用于需要汇总线程计算结果的场景
示例:
from concurrent.futures import ThreadPoolExecutor <p>def square(x): return x * x</p><p>with ThreadPoolExecutor(max_workers=3) as executor: futures = [executor.submit(square, i) for i in range(5)] results = [f.result() for f in futures]</p><p>print(results) # [0, 1, 4, 9, 16]</p>
基本上就这些常见方案。选择哪种方式取决于具体需求:若需频繁读写共享状态,用 Lock 配合全局变量;若强调解耦和顺序通信,优先选 Queue;若要隔离上下文,用 threading.local;若关注任务结果收集,concurrent.futures 更简洁。关键是理解每种机制的适用边界,避免竞态条件和死锁。









