Imagine several friends using one refrigerator: one puts something in, and the others can find it there. Shared memory works similarly for concurrent tasks. A common memory area lets tasks exchange data by reading and writing it, rather than sending messages to one another. section 5.2 section 5.1
Threads in one program can share objects; tasks on different processor cores can refer to the same physical memory. The operating system helps allocate shared memory but does not handle each exchange. That makes communication fast and avoids extra copying. It also leaves tasks responsible for coordinating access when they might change the same data. section 5.2
A producer and a consumer
A Python producer thread writes values into a shared array, while a consumer thread reads them. The consumer waits when a value is not yet available. Both threads use the same array, but sharing it does not by itself resolve conflicts if tasks try to update the same data. section 5.2
# Chapter 5/shared_ipc.py
import time
from threading import Thread, current_thread
SIZE = 5
shared_memory = [-1] * SIZE #1
class Producer(Thread):
def run(self) -> None:
self.name = "Producer"
global shared_memory
for i in range(SIZE):
print(f"{current_thread().name}: Writing {int(i)}")
shared_memory[i - 1] = i #2
class Consumer(Thread):
def run(self) -> None:
self.name = "Consumer"
global shared_memory
for i in range(SIZE):
while True: #3
line = shared_memory[i] #3
if line == -1: #3
print(f"{current_thread().name}: Data not available\n" #3
f"Sleeping for 1 second before retrying") #3
time.sleep(1) #3
continue #3
print(f"{current_thread().name}: Read: {int(line)}") #3
break #3
def main() -> None:
threads = [
Consumer(),
Producer(),
]
for thread in threads: #4
thread.start() #4
for thread in threads: #5
thread.join() #5
if __name__ == "__main__":
main()
The Python listing shows a producer and consumer communicating through a shared array. section 5.2
Shared memory is useful when copying large amounts of data would be costly. For example, matrix-calculation tasks can read the same input matrices while computing separate output elements. When tasks need to modify shared data, locks can protect access, but they add overhead; message passing is another way to avoid sharing the data. section 5.6 section 13.5 section 9.10

