Multiprocessing in Python
Multiprocessing allows the execution of multiple processes simultaneously, each with its own memory space. Below is a practical example demonstrating how to create and manage procseses using the multiprocessing module.
import os
import time
import multiprocessing
def vocal_performance(count, artist):
print('Child process ID:', os.getpid())
print('Parent process ID:', os.getppid())
for i in range(count):
print(f'{artist} performing song... {i + 1} time(s)')
time.sleep(0.5)
def movement_routine(count, performer):
print('Child process ID:', os.getpid())
for i in range(count):
print(f'{performer} dancing...')
time.sleep(0.5)
if __name__ == '__main__':
print('Main process ID:', os.getpid())
process1 = multiprocessing.Process(target=vocal_performance, args=(3, 'Ming'))
process1.daemon = True
process2 = multiprocessing.Process(target=movement_routine, kwargs={'count': 2, 'performer': 'Xiaohong'})
process1.start()
process2.start()
Multithreading in Python
Multithreading enables concurrent execution of threads within a single process, sharing the same memory space. This is particularly useful for I/O-bound tasks. Below is a sample implementation using the threading module.
import threading
import time
def vocal_loop(repetitions):
for i in range(repetitions):
print('Singing...')
time.sleep(0.2)
def choreography_loop(repetitions):
for i in range(repetitions):
print('Dancing...')
time.sleep(0.2)
if __name__ == '__main__':
thread1 = threading.Thread(target=vocal_loop, args=(3,), daemon=True)
thread2 = threading.Thread(target=choreography_loop, kwargs={'repetitions': 5})
thread1.start()
thread2.start()
Key Concepts and Use Cases
- Shared Memory: Threads within the same process share memory and resourcse, enabling fast communication.
- Low Overhead: Thread creation and context switching are faster compared to processes.
- Global Interpreter Lock (GIL): Python's GIL restricts true parallelism in CPU-bound tasks but is less impactful in I/O-bound scenarios.
- Data Synchronization: Shared data access requires synchronization mechanisms like locks and semaphores.
Applicable Scenarios
- I/O-bound operations such as file handling, network requests, and data streaming.
- Applications requiring shared state between concurrent tasks.