PyDocs

Nav

Concurrent Execution

SharedMemory

  • SharedMemory(name=None, create=False, size=0, *, track=True)
Creates a new shared memory block or attaches to an existing
shared memory block.

Every shared memory block is assigned a unique name.  This enables
one process to create a shared memory block with a particular name
so that a different process can attach to that same shared memory
block using that same name.

As a resource for sharing data across processes, shared memory blocks
may outlive the original process that created them.  When one process
no longer needs access to a shared memory block that might still be
needed by other processes, the close() method should be called.
When a shared memory block is no longer needed by any process, the
unlink() method should be called to ensure proper cleanup.
Changed in 3.13
  • 3.13: Added the track parameter.
Members of SharedMemory

b

buf
A memoryview of contents of the shared memory block.

c

close
Closes access to the shared memory from this instance but does not destroy the shared memory block.

n

name
Unique name that identifies the shared memory block.

s

size
Size in bytes.

u

unlink
Requests that the underlying shared memory block be destroyed.
1 Example
>>> from multiprocessing import shared_memory
>>> shm_a = shared_memory.SharedMemory(create=True, size=10)
>>> type(shm_a.buf)
<class 'memoryview'>
>>> buffer = shm_a.buf
>>> len(buffer)
10
>>> buffer[:4] = bytearray([22, 33, 44, 55])  # Modify multiple at once
>>> buffer[4] = 100                           # Modify single byte at a time
>>> # Attach to an existing shared memory block
>>> shm_b = shared_memory.SharedMemory(shm_a.name)
>>> import array
>>> array.array('b', shm_b.buf[:5])  # Copy the data into a new array.array
array('b', [22, 33, 44, 55, 100])
>>> shm_b.buf[:5] = b'howdy'  # Modify via shm_b using bytes
>>> bytes(shm_a.buf[:5])      # Access via shm_a
b'howdy'
>>> shm_b.close()   # Close each SharedMemory instance
>>> shm_a.close()
>>> shm_a.unlink()  # Call unlink only once to release the shared memory
from the Python docs
See Also
No see-alsos for multiprocessing.shared_memory/SharedMemory
0 Notes
No notes for SharedMemory