Lab4 Multiprocessing in Python
Lab4 Multiprocessing in Python
Introduction
Python's multiprocessing module allows you to create processes that run concurrently, taking
advantage of multiple CPU cores. This is particularly useful for tasks that are CPU-bound, as it
can significantly speed up processing time by utilizing all available cores.
Prerequisites
Lab Objectives
1. Basics of Multiprocessing
import multiprocessing
2. Creating a Process
import multiprocessing
def worker_function():
print("Hello from a new process!")
if __name__ == "__main__":
process = multiprocessing.Process(target=worker_function)
process.start() # Starts the process
process.join() # Waits for the process to complete
print("Main process complete.")
Explanation:
• target specifies the function that the new process will run.
• start() launches the process.
• join() ensures that the main process waits until the new process finishes.
Pool allows you to manage multiple worker processes and distribute tasks among them.
import multiprocessing
def square(n):
return n * n
if __name__ == "__main__":
with multiprocessing.Pool(processes=4) as pool:
numbers = [1, 2, 3, 4, 5]
results = pool.map(square, numbers)
print("Squares:", results)
Explanation:
4. Inter-Process Communication
Queue is a thread- and process-safe FIFO queue for communication between processes.
Example: Using Queue
import multiprocessing
def producer(queue):
for i in range(5):
queue.put(i)
print(f"Produced: {i}")
def consumer(queue):
while not queue.empty():
item = queue.get()
print(f"Consumed: {item}")
if __name__ == "__main__":
queue = multiprocessing.Queue()
p1 = multiprocessing.Process(target=producer, args=(queue,))
p2 = multiprocessing.Process(target=consumer, args=(queue,))
p1.start()
p1.join() # Ensure the producer finishes before starting the consumer.
p2.start()
p2.join()
Explanation:
• Queue is used to store items produced by one process and consumed by another.
• put() adds an item to the queue, while get() retrieves it.
Lock can prevent race conditions when multiple processes try to access shared resources.
import multiprocessing
if __name__ == "__main__":
lock = multiprocessing.Lock()
counter = multiprocessing.Value('i', 0) # Shared memory object of type
integer.
for p in processes:
p.start()
for p in processes:
p.join()
Explanation:
• Lock ensures that only one process can increment the counter at a time.
• multiprocessing.Value() is used for sharing data between processes.
Example:
def add_to_value(val):
val.value += 1
if __name__ == "__main__":
val = Value('i', 0) # 'i' means integer
processes = [Process(target=add_to_value, args=(val,)) for _ in
range(10)]
for p in processes:
p.start()
for p in processes:
p.join()
7. Exercises
• Write a program that calculates the factorial of numbers using multiple processes.
• Use a Pool to divide the workload among processes.
7.4 Exercise 4: Discuss the challenges and advantages of parallel programming in Python.
Include examples of scenarios where it would be beneficial to use multiprocessing or
threading.
8. Summary
9. Additional Resources