Threads run concurrently within the same process, sharing memory space. Python's Global Interpreter Lock (GIL) limits threads to one execution at a time, making it ideal for I/O-bound tasks but not for CPU-intensive ones.
Example: A Simple Threaded Program
import threading def print_numbers(): for i in range(5): print(f"Number: {i}") # Create and start threads thread1 = threading.Thread(target=print_numbers) thread2 = threading.Thread(target=print_numbers) thread1.start() thread2.start() thread1.join() thread2.join()
Multiprocessing creates separate processes with individual memory space, bypassing the GIL. It’s best for CPU-bound tasks, like data processing or simulations.
Example: Multiprocessing Basics
from multiprocessing import Process def print_numbers(): for i in range(5): print(f"Number: {i}") if __name__ == "__main__": process1 = Process(target=print_numbers) process2 = Process(target=print_numbers) process1.start() process2.start() process1.join() process2.join()
With threads, Python multitasks within a single process. With processes, Python achieves true parallelism across multiple cores. Together, they make your code efficient and scalable.
_ ? Cheers to mastering concurrency in Python!_
The above is the detailed content of Python Multithreading and Multiprocessing. For more information, please follow other related articles on the PHP Chinese website!