Giving access to shared memory after child processes have already started

后端 未结 3 766
太阳男子
太阳男子 2020-12-09 05:41

How do I give child processes access to data in shared memory if the data is only available after the child processes have been spawned (using multiprocessing.Process)?

3条回答
  •  再見小時候
    2020-12-09 06:02

    I think you are looking for mmap module

    concerning the serializiation of data this question answer of course if you hope to avoid copy I have not the solution

    EDIT

    in fact you can use the non stdlib _mutliprocessing module in CPython 3.2 to have the address of the mmap object and use it with from_address of a ctypes object it is what in fact what does RawArray in fact of course you should not try to resize the mmap object as the address of mmap may change in this case

    import mmap
    import _multiprocessing
    from ctypes import Structure,c_int
    
    map = mmap.mmap(-1,4)
    class A(Structure):
        _fields_ = [("x", c_int)]
    x = _multiprocessing.address_of_buffer(map)
    b=A.from_address(x[0])
    b.x = 256
    
    >>> map[0:4]
    '\x00\x01\x00\x00'
    

    to expose the memory after the child is created you have to map your memory with a real file that is calling

    map = mmap.mmap(open("hello.txt", "r+b").fileno(),4)
    

提交回复
热议问题