Processes and Threads: The Boss with N Clones
The article explains processes as independent execution units and threads as lightweight CPU‑scheduled workers, using a boss‑and‑employees metaphor, code samples in Python and Java, practical scenarios, common pitfalls like race conditions and deadlocks, and guidance on when to choose multiprocessing versus multithreading.
Process: an Independent Application
Process is a program’s execution instance and the basic unit of resource allocation. Each process has its own address space, memory, file handles, and network connections, so a crash in one process does not affect others. Creating or destroying a process incurs relatively high overhead because the operating system must allocate separate resources.
# Open a browser = start a process
# Open two browsers = start two processes
# Each process has its own "independent room"
# Variables in Process A do not affect Process BIndependent address space: a process crash does not impact others.
Resource allocation unit: memory, file handles, network connections, etc.
High startup cost: requires separate resource allocation.
Thread: the Employee Inside a Process
Thread is the basic unit of CPU scheduling; a single process can contain multiple threads. Threads share the process’s resources but have their own execution context.
# Single‑thread: one employee does one task
# Multi‑thread: one employee can handle many tasks simultaneouslyMetaphor Upgrade
Boss (Process) Zhang San:
├── Secretary Thread 1: answer calls
├── Assistant Thread 2: handle emails
├── Accountant Thread 3: bookkeeping
└── Runner Thread 4: deliver documents
All threads share the boss’s resources (office, computer, accounts) but perform different jobs.Process‑Thread Relationship
Process (Process)
├── Thread 1
├── Thread 2
├── Thread 3
└── ... (many possible)
Thread = execution unit of a process
Process = container for threadsKey Differences
Resource allocation: process is the allocation unit; thread shares process resources.
Overhead: process creation/destruction is costly; thread creation/destruction is cheap.
Communication: processes use IPC (pipes, message queues); threads read/write shared memory directly.
Isolation: a process crash does not affect others; a thread crash can bring down the whole process.
Parallelism: multiple processes can run in parallel; multiple threads run in parallel only within the same process.
How Multithreading Works
Fake Parallelism: Time‑Slice Rotation
Single‑core CPU can execute only one thread at a time, but fast context switches give the illusion of simultaneity.
Time slice 1 (10 ms): Thread A runs → pause
Time slice 2 (10 ms): Thread B runs → pause
Time slice 3 (10 ms): Thread C runs → pause
Time slice 4 (10 ms): Thread A resumes …Real Parallelism: Multi‑core CPU
4‑core CPU = 4 true "employees"
Each core can run a thread simultaneously → true parallel execution.Code Samples
Python Multithreading
import threading
import time
def task(name):
print(f"线程 {name} 开始")
time.sleep(1)
print(f"线程 {name} 完成")
# Create 3 threads
t1 = threading.Thread(target=task, args=("A",))
t2 = threading.Thread(target=task, args=("B",))
t3 = threading.Thread(target=task, args=("C",))
# Start
t1.start()
t2.start()
t3.start()
# Wait for completion
t1.join()
t2.join()
t3.join()
print("全部完成!")Java Multithreading
public class MyThread extends Thread {
public void run() {
System.out.println("线程运行中...");
}
}
public class Main {
public static void main(String[] args) {
MyThread t = new MyThread();
t.start(); // 启动线程
// 主线程继续执行
System.out.println("主线程也在跑");
}
}Why Use Multithreading?
Scenario 1: Doing Multiple Tasks Simultaneously
# Download 10 files
# Single‑thread: one after another – slow
# Multi‑thread: download in parallel – much fasterScenario 2: Keep UI Responsive
# Button click runs on the main thread
# If the main thread performs a long operation, the UI freezes
# Solution: move the heavy work to a worker threadScenario 3: Server Concurrency
Server receives 1000 requests:
- Single‑thread: handle one by one – slow
- Multi‑thread / Multi‑process: handle many at once – fastCommon Pitfalls
Race Condition
Two threads modify the same variable:
Thread A reads count=0 → count+1 → count=1
Thread B reads count=0 → count+1 → count=1 (should be 2!)Deadlock
Thread A holds lock1 and waits for lock2
Thread B holds lock2 and waits for lock1
Result: both threads block forever.Thread Safety
# Non‑thread‑safe example
counter = 0
for i in range(1000000):
counter += 1 # possible race condition
# Thread‑safe version using a lock
from threading import Lock
lock = Lock()
counter = 0
for i in range(1000000):
with lock:
counter += 1Process vs. Thread: When to Choose Which
CPU‑intensive tasks: prefer multiple processes (avoid GIL in Python).
IO‑intensive tasks: prefer multithreading.
Need strong isolation: use multiple processes.
Heavy shared data: use multithreading (shared memory).
Memory‑sensitive environments: multithreading saves memory.
Python note: Python’s Global Interpreter Lock (GIL) makes multithreading unsuitable for CPU‑bound work but fine for IO‑bound work.
Conclusion
Process = a company
Thread = employees in the company
A company (process) can have many employees (threads).
Employees share company resources but work independently.
Single‑core CPU = a boss who schedules work round‑robin.
Multi‑core CPU = multiple bosses working at the same time.Key takeaways:
Process is the resource allocation unit; thread is the CPU scheduling unit.
Threads share process resources and have low creation overhead.
Single‑core CPUs provide "fake parallelism" via time slicing; multi‑core CPUs provide true parallelism.
Multithreading requires careful handling of race conditions, deadlocks, and thread safety.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
IT Learning Made Simple
Learn IT: using simple language and everyday examples to study.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
