示例工程 21-free-threading-concurrency-choice

21-free-threading-concurrency-choice/04-shared-memory/shared_memory.py

python · 0.9 KB

"""演示 multiprocessing.shared_memory 与 numpy 的零拷贝共享。"""
 
from __future__ import annotations
 
from multiprocessing import shared_memory
 
 
def shared_demo(values: list[int]) -> list[int]:
    import numpy as np
 
    array = np.array(values, dtype=np.int64)
    block = shared_memory.SharedMemory(create=True, size=array.nbytes)
    try:
        shared = np.ndarray(array.shape, dtype=array.dtype, buffer=block.buf)
        shared[:] = array
        shared[0] = 99
        result: list[int] = shared.tolist()
        return result
    finally:
        block.close()
        block.unlink()
 
 
def main() -> None:
    try:
        import numpy  # noqa: F401  # 仅检测依赖是否安装
    except ImportError:
        print("numpy missing: uv sync --group science")
        return
    print(f"shared: {shared_demo([1, 2, 3, 4])}")
 
 
if __name__ == "__main__":
    main()