A process is an independent program in execution with its own memory space. A thread is the smallest unit of execution within a process. Multiple threads within the same process share the process's resources.
What each thread has (private): Thread ID, program counter, register set, stack
What threads share (with process): Code section, data section, heap, open files, signals
| Feature | Process | Thread |
|---|---|---|
| Memory | Separate address space | Shared address space (within process) |
| Resources | Own file handles, I/O, etc. | Shares process resources |
| Creation overhead | High (fork/exec) | Low (lightweight) |
| Communication | IPC (pipes, sockets, shared memory) | Direct (shared memory) |
| Isolation | Crash doesn't affect other processes | Crash can kill entire process |
| Context switch | Expensive (full address space switch) | Cheaper (same address space) |
| Feature | User-Level Threads | Kernel-Level Threads |
|---|---|---|
| Management | Managed by user-space thread library | Managed by OS kernel |
| Kernel awareness | Kernel sees only one process | Kernel knows about each thread |
| Context switch | Fast (no kernel mode switch) | Slower (kernel involvement) |
| Blocking | If one thread blocks, all threads block | Other threads can continue |
| Parallelism | Cannot run on multiple CPUs simultaneously | Can run on multiple CPUs |
| Examples | POSIX Pthreads (user-space), Java green threads | Windows threads, Linux pthreads (kernel) |
Threading models define how user threads map to kernel threads:
A thread pool is a collection of pre-created threads waiting for tasks. Instead of creating a new thread for each task (expensive), tasks are submitted to the pool and executed by available threads.
Benefits:
Thread pool parameters:
A race condition occurs when two or more threads access shared data concurrently and the result depends on the order of execution. This leads to unpredictable, incorrect behavior.
Example: Two threads both read a counter (value=5), both increment it, and both write back. Expected result: 7. Actual result: 6 (one increment is lost).
Solutions:
Explore 500+ free tutorials across 20+ languages and frameworks.