Manage Shared Memory Ownership and Synchronization
Core idea
SharedMemory exposes a named byte buffer that another process can attach to. Unlike message passing, both attachments can view the same storage. Agree on a byte layout and synchronize conflicting accesses. Each attachment closes its handle; the owner arranges one unlink when the block is no longer needed. On Windows unlink has no effect and handles govern deletion.
from multiprocessing.shared_memory import SharedMemoryif __name__ == '__main__': owner = SharedMemory(create=True, size=3) try: owner.buf[:] = b'abc' peer = SharedMemory(name=owner.name) try: peer.buf[0] = ord('Z') print(bytes(owner.buf[:3])) finally: peer.close() finally: owner.close() owner.unlink()Two attachments in one process observe the same bytes. The owner unlinks only after the peer closes.
Expected output:
b'Zbc'Protect a shared counter
from multiprocessing import get_contextif __name__ == '__main__': ctx = get_context('spawn') count = ctx.Value('i', 2) with count.get_lock(): count.value += 3 print(count.value)The outer lock protects the entire compound update; the default synchronized Value uses a recursive lock.
Expected output:
5Common mistake
Shared memory does not provide a transaction or automatic synchronization. Release exported memoryviews before closing, do not unlink while consumers still need the region, and coordinate resource tracking across independently launched processes.
Practice
Design a four-byte shared counter with one owner and two workers using a process lock. Specify when each handle closes and who unlinks.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Shared memory
Check your understanding of shared memory.
What is printed?
from multiprocessing import Valuev=Value("i",4)with v.get_lock(): v.value+=2print(v.value)What is printed?
data=bytearray(b"abc")view=memoryview(data)view[1]=ord("X")print(bytes(data))Who should arrange unlink for shared memory?
Does a shared buffer guarantee atomic read-modify-write?