Exp 3
Exp 3
a. Pipes (pipe.py)
import multiprocessing
def child_process(conn):
print("Child process started.") # Debugging print
# Receive the message from the parent process
msg_from_parent = conn.recv()
print(f"Child received: {msg_from_parent}")
def parent_process():
print("Parent process started.") # Debugging print
# Create a pipe
parent_conn, child_conn = multiprocessing.Pipe()
if __name__ == "__main__":
print("Main execution started.") # Debugging print
parent_process()
output:
Shared Memory
Creates a multiprocessing.Array to hold the shared
memory.
Writer process Writes a message to the shared memory.
Saves the shared memory contents to a file
(shared_memory.bin) so it can be read later.
Reader process Reads the saved shared memory data
from the file and prints it.
import multiprocessing
def writer(shared_memory):
# Write data to the shared memory
data = b'Hello from writer process!'
# Ensure the data fits within the allocated size
shared_memory[:len(data)] = data
def reader(shared_memory):
# Read data from the shared memory
data_read = bytes(shared_memory[:4096])
print('Data read from shared memory:',
data_read.decode().strip())
if __name__ == "__main__":
# Create a shared memory object
shared_memory = multiprocessing.Array('c', 4096) #
Create a shared memory array with 4096 bytes
MESSAGE PASSING:
Message passing is a method of inter-process communication
(IPC) where processes send and receive messages to each
other. In Python, one of the common ways to implement
message passing between processes is by using the
multiprocessing.Queue class from the multiprocessing module.
import multiprocessing
import time
def sender(queue):
messages = [
"Message 1 from sender",
"Message 2 from sender",
"Message 3 from sender"
]
for msg in messages:
queue.put(msg) # Put each message onto the queue
print(f"Sender: Sent '{msg}'")
time.sleep(1) # Simulate some delay between messages
def receiver(queue):
while True:
msg = queue.get() # Get the next message from the
queue
if msg == "END": # End message signal to break the loop
break
print(f"Receiver: Received '{msg}'")
if __name__ == "__main__":
queue = multiprocessing.Queue()