Python 3.8 新增 multiprocessing.SharedMemory 支持共享内存
source link: https://www.linuxzen.com/python-38-shared-memory.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
Python 在 2019-02-25 释出了 3.8 早期预览版 3.8.0a2,其中新增了 multiprocessing.SharedMemory 用以支持共享内存,大大提高多进程之间通信效率。简单看了一下实现代码主要涉及如下 Python 模块
在 POSIX 平台下共享内存创建过程如下:
- 基于
tmpfs
打开或创建具名(文件名)的共享内存,得到文件描述符 - 通过
mmap
将文件描述符映射进程的内存地址空间 - 通过
memoryview
直接访问经过mmap
映射后的的内存地址空间
memoryview
通过如下方式使用:
s = bytearray(b'aaa')
m = memoryview(s)
m[0] = 98
print(s) # outputs: bytearray(b'baa')
当上面代码执行 m[0] = 98
时实际上调用的是 C 代码 memory_ass_sub,然后调用 PACK_SINGLE 通过 memcpy
覆盖指针原有的值。
所以直接操作 multiprocessing.SharedMemory
会产生数据竞争,不应该直接使用,应该使用 multiprocessing.Value 和 multiprocessing.Array 这种更高层的抽象,锁在这一层级实现。
更多关于共享内存参见:
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK