Core Idea
Process = chương trình đang chạy (isolated)
So sánh nhanh
| Process | Thread |
| Isolation | Strong | Weak |
| Memory | Riêng biệt | Shared |
| Communication | IPC (slow) | Shared memory (fast) |
| Crash impact | Không ảnh hưởng process khác | Có thể crash toàn bộ process |
| Creation cost | Cao | Thấp |
| Context switch | Nặng | Nhẹ |
| Use case | App độc lập | Concurrent tasks |
Process là gì?
Định nghĩa
-
Một instance của program đang chạy
-
Có:
Ví dụ
-
Chrome browser
-
MySQL server
-
Node.js app
Ưu điểm
-
Isolation cao → an toàn
-
Crash không lan sang process khác
-
Security tốt
Nhược điểm
-
Tốn memory
-
IPC (inter-process communication) phức tạp
-
Context switch nặng
Thread là gì?
Định nghĩa
-
Đơn vị thực thi bên trong process
-
Các thread:
Ví dụ
-
Web server xử lý nhiều request cùng lúc
-
Worker threads trong backend
Ưu điểm
-
Nhẹ, tạo nhanh
-
Giao tiếp nhanh (shared memory)
-
Hiệu quả cho concurrency
Nhược điểm
-
Race condition
-
Deadlock
-
Debug khó
-
Crash 1 thread → có thể chết cả process
Memory Model
Process
Process A → Memory A
Process B → Memory B
❌ Không truy cập trực tiếp
Thread
Process
├── Thread 1
├── Thread 2
└── Thread 3
→ Shared memory
Context Switching
Process switching
-
Save/restore toàn bộ state
-
Chậm hơn
-
Chỉ switch execution context
-
Nhanh hơn
Communication
Process (IPC)
-
Pipe
-
Socket
-
Shared memory (phức tạp)
Thread
Common Problems (Thread)
Race condition
-
2 thread cùng update data
Deadlock
Starvation
Use Cases
Process
-
Microservices (mỗi service 1 process)
-
Container (Docker)
-
Multi-app system
Thread
-
Web server handling requests
-
Background workers
-
Parallel computation
Threading Models (important)
Single-thread
-
Simple
-
Không tận dụng multi-core
Multi-thread
-
Parallel execution
-
Phức tạp hơn
Event loop (Node.js style)
-
Single thread + async I/O
-
Không dùng thread nhiều
Process vs Thread trong Backend
Node.js
-
Single thread (event loop)
-
Scale bằng:
Java / Go
-
Multi-thread / goroutines
-
Concurrent processing mạnh
Python
-
GIL → hạn chế multi-thread CPU-bound
-
Dùng multi-process cho parallel
Interview Insights
Khi nào dùng Process?
-
Isolation
-
Security
-
Heavy workloads
Khi nào dùng Thread?
-
High concurrency
-
Shared data
-
Performance
One-liner
Process để cô lập, Thread để tăng concurrency
Mapping với System Design
| Concept | Mapping |
| Process | Microservice |
| Thread | Worker / request handler |
| IPC | API / network call |
| Shared memory | Cache |