Process and threads¶
- Program: Sequence of instructions written in a programming language.
- Process: Process is an instance of a program that is being executed.
- Separated memory spaces.
- One process cannot corrupt another one.
- Thread: Is an unity of execution within a process.
Import packages¶
Multithreading¶
- Concurrent execution
- I/O bound tasks
Simulate some I/O expensive task.
Execute synchronously.
Task 0: Starting I/O operation...
Task 0: Finished I/O operation.
Task 1: Starting I/O operation...
Task 1: Finished I/O operation.
Task 2: Starting I/O operation...
Task 2: Finished I/O operation.
Task 3: Starting I/O operation...
Task 3: Finished I/O operation.
Task 4: Starting I/O operation...
Task 4: Finished I/O operation.
Operation took 5 seconds
Execute the same tasks in parallel with threads.
Task 0: Starting I/O operation...
Task 1: Starting I/O operation...
Task 2: Starting I/O operation...
Task 3: Starting I/O operation...
Task 4: Starting I/O operation...
Task 0: Finished I/O operation.
Task 1: Finished I/O operation.
Task 2: Finished I/O operation.
Task 3: Finished I/O operation.
Task 4: Finished I/O operation.
Operation took 1 seconds
Thread Pool Executor¶
Multiprocessing¶
- Run processes in parallel
- CPU bound tasks
- Use multiple cores of CPU