Python多线程内存共享方式包括:1. 全局变量配合Lock确保线程安全,适用于简单数据共享;2. queue.Queue实现线程安全通信,适合生产者-消费者模型;3. threading.local为线程提供独立数据副本,避免状态冲突;4. multiprocessing.shared_memory(Python 3.8+)共享大块二进制数据如NumPy数组,需手动同步。应根据场景选择合适机制并处理线程安全。

Python多线程中,由于全局解释器锁(GIL)的存在,虽然多线程在CPU密集型任务中无法真正并行执行,但在IO密集型场景下仍具有实用价值。而在线程之间共享数据是常见需求。以下是几种常用的内存共享方式及其使用场景和注意事项。
最直接的共享方式是使用模块级的全局变量。所有线程都可以读写同一个变量,但由于Python对象的可变性不同,需注意线程安全。
说明: - 对于不可变类型(如int、str),直接赋值会创建新对象,其他线程不可见。 - 可变类型(如list、dict)可以在原地修改,多个线程看到的是同一对象。建议:
import threading </li></ul><p>data = [] lock = threading.Lock()</p><p>def add_item(value): with lock: data.append(value)</p><p>t1 = threading.Thread(target=add_item, args=(1,)) t2 = threading.Thread(target=add_item, args=(2,)) t1.start(); t2.start() t1.join(); t2.join()
queue.Queue 是线程安全的队列实现,适合生产者-消费者模型。
立即学习“Python免费学习笔记(深入)”;
优点: - 内置锁机制,无需手动加锁。 - 支持阻塞操作(put/get 可设置超时)。 - 可控制缓冲区大小,防止内存溢出。使用示例:
import queue
import threading
<p>q = queue.Queue(maxsize=5)</p>
<div class="aritcle_card">
<a class="aritcle_card_img" href="/ai/1146">
<img src="https://img.php.cn/upload/ai_manual/000/000/000/175680088775482.png" alt="存了个图">
</a>
<div class="aritcle_card_info">
<a href="/ai/1146">存了个图</a>
<p>视频图片解析/字幕/剪辑,视频高清保存/图片源图提取</p>
<div class="">
<img src="/static/images/card_xiazai.png" alt="存了个图">
<span>17</span>
</div>
</div>
<a href="/ai/1146" class="aritcle_card_btn">
<span>查看详情</span>
<img src="/static/images/cardxiayige-3.png" alt="存了个图">
</a>
</div>
<p>def producer():
for i in range(5):
q.put(i) # 自动阻塞当队列满
print(f"Produced {i}")</p><p>def consumer():
while True:
item = q.get()
if item is None:
break
print(f"Consumed {item}")
q.task_done()虽然这不是“共享”,但用于避免共享冲突的一种策略:为每个线程提供独立的数据副本。
适用场景: - 需要每个线程有独立状态(如数据库连接、用户上下文)。 - 防止变量污染。示例:
import threading
<p>local_data = threading.local()</p><p>def process(name):
local_data.name = name
print(f"Hello {local_data.name}")</p><p>t1 = threading.Thread(target=process, args=("Alice",))
t2 = threading.Thread(target=process, args=("Bob",))虽然名字叫 multiprocessing,但从Python 3.8起,shared_memory 模块也可被线程使用,尤其适合共享大块二进制数据(如NumPy数组)。
特点: - 共享真实内存区域,节省复制开销。 - 需手动管理生命周期(创建/释放)。 - 线程间访问仍需同步机制。示例(共享NumPy数组):
from multiprocessing import shared_memory import numpy as np import threading <h1>创建共享内存</h1><p>a = np.array([1, 2, 3, 4]) shm = shared_memory.SharedMemory(create=True, size=a.nbytes) buf = np.ndarray(a.shape, dtype=a.dtype, buffer=shm.buf) buf[:] = a[:]</p><p>def modify_array(offset): buf[offset] += 10</p><p>t1 = threading.Thread(target=modify_array, args=(0,)) t2 = threading.Thread(target=modify_array, args=(1,)) t1.start(); t2.start() t1.join(); t2.join()</p><p>print(buf) # 查看结果 shm.close() # 使用完释放 shm.unlink() # 删除共享内存
基本上就这些常见的Python多线程内存共享方案。根据实际需求选择:简单共享用全局变量加锁,通信用Queue,隔离状态用threading.local,大数据用shared_memory。关键是处理好线程安全问题。
以上就是Python多线程内存共享方案 Python多线程共享内存的几种方式的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号