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密集场景下仍广泛使用多线程,因此数据共享与安全尤为重要。
多个线程可以访问同一个全局变量,但直接修改会导致数据竞争。使用 threading.Lock 可避免冲突。
示例代码:
<pre class="brush:php;toolbar:false;">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>
queue.Queue 是线程安全的队列,非常适合生产者-消费者模型,无需手动加锁。
示例:生产者和消费者共享数据
<pre class="brush:php;toolbar:false;">import threading
import queue
import time
<p>q = queue.Queue(maxsize=5)</p>
<div class="aritcle_card">
<a class="aritcle_card_img" href="/ai/1101">
<img src="https://img.php.cn/upload/ai_manual/001/503/042/68b6c6af75d71275.png" alt="腾讯智影-AI数字人">
</a>
<div class="aritcle_card_info">
<a href="/ai/1101">腾讯智影-AI数字人</a>
<p>基于AI数字人能力,实现7*24小时AI数字人直播带货,低成本实现直播业务快速增增,全天智能在线直播</p>
<div class="">
<img src="/static/images/card_xiazai.png" alt="腾讯智影-AI数字人">
<span>73</span>
</div>
</div>
<a href="/ai/1101" class="aritcle_card_btn">
<span>查看详情</span>
<img src="/static/images/cardxiayige-3.png" alt="腾讯智影-AI数字人">
</a>
</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>有时需要每个线程拥有独立的数据副本,避免交叉污染。threading.local 提供线程本地存储。
示例:
<pre class="brush:php;toolbar:false;">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>concurrent.futures 提供高级接口,可通过 Future 对象安全获取线程返回值。
示例:
<pre class="brush:php;toolbar:false;">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 更简洁。关键是理解每种机制的适用边界,避免竞态条件和死锁。
以上就是Python多线程如何共享数据 Python多线程数据安全传递方案的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号