Mastering Processes and Threads: 19 Essential OS Concepts Explained
This comprehensive guide covers the fundamentals of processes and threads, their definitions, relationships, creation, lifecycle, scheduling strategies, context switching, inter‑process communication methods, and practical C/C++ examples, providing a deep dive into operating‑system concepts for developers and interview preparation.
What Is a Process?
A process is an executing instance of a program. It has its own address space, registers, and variables. The program code is static; the process is the dynamic execution of that code.
Process vs. Program
A program is a file containing executable code. When the operating system creates a process from that program, the process obtains its own resources and execution state. Multiple processes can be created from the same program.
Process Creation
Typical creation events include system boot, a user launching an application, or a running process invoking a system call such as fork() on UNIX‑like systems.
#include <stdio.h>
#include <unistd.h>
int main() {
pid_t id = fork();
if (id < 0) {
perror("fork");
} else if (id == 0) {
printf("Child process
");
} else {
printf("Parent process
");
}
return 0;
}After fork() the parent and child have separate address spaces. Modern kernels use copy‑on‑write so pages are shared until one side modifies them.
Process Termination
A process can exit voluntarily with exit() or be terminated by signals (e.g., SIGKILL). Example of an error exit:
#include <stdio.h>
#include <stdlib.h>
void Func() {
if (error) {
exit(1);
}
}
int main() { Func(); }Process Control Block (PCB)
The OS maintains a PCB for each process. It stores:
Process identifiers (PID, PPID, UID)
CPU state (program counter, registers, stack pointer)
Memory management information (page tables, segment descriptors)
Open file descriptors and I/O status
Scheduling information (priority, state)
IPC identifiers (message queues, semaphores, shared memory)
Process States
Running : currently executing on the CPU.
Ready : waiting for CPU allocation.
Blocked (Waiting) : waiting for I/O, a signal, or another event.
Process Scheduling
The scheduler selects a ready process to run. Common algorithms:
First‑Come‑First‑Served (FCFS)
Shortest Job First (SJF)
Shortest Remaining Time First (SRTF)
Round‑Robin (RR)
Priority Scheduling
Multilevel Queue
Lottery Scheduling
Context Switch
A context switch saves the state of the currently running task (registers, program counter, stack pointer) and restores the state of the next task. Frequent switches must be fast to avoid performance loss.
Signals, Semaphores, and Mutexes
Signals are asynchronous notifications (e.g., SIGINT) without data payload.
Semaphores are counting variables used for synchronization (P/V operations).
Mutexes provide mutual exclusion for critical sections; they are binary semaphores that protect shared resources.
Inter‑Process Communication (IPC)
Because processes have separate address spaces, they communicate via kernel‑mediated mechanisms:
Anonymous Pipe ( pipe()) – parent‑child, half‑duplex.
#include <unistd.h>
int fd[2];
pipe(fd);
pid_t pid = fork();
if (pid == 0) { /* child */ close(fd[1]); read(fd[0], buf, sizeof(buf)); }
else { /* parent */ close(fd[0]); write(fd[1], "msg", 4); }Named Pipe (FIFO) ( mkfifo()) – no parent‑child relationship required.
Message Queue – typed messages, multiple readers/writers.
#include <sys/msg.h>
struct Msg { long type; char text[20]; };
int id = msgget(1024, 0666|IPC_CREAT);
Msg m; m.type = 2; strcpy(m.text, "hello"); msgsnd(id, &m, sizeof(m.text), 0);
msgrcv(id, &m, sizeof(m.text), 2, 0);
msgctl(id, IPC_RMID, 0);Shared Memory – fastest IPC; processes map the same physical memory (POSIX shm_open, System V shmget, or mmap).
Sockets – network or local (UNIX domain) communication.
Files – processes read/write a common file.
Multithreading in C/C++
POSIX thread API: pthread_create – create a new thread. pthread_exit – terminate the calling thread. pthread_join – wait for a specific thread. pthread_yield – voluntarily give up the CPU. pthread_attr_init / pthread_attr_destroy – manage thread attributes.
C++11 provides std::thread and std::async:
#include <iostream>
#include <thread>
void f() { std::cout << "a" << std::endl; }
int main() {
std::thread t(f);
t.detach();
std::this_thread::sleep_for(std::chrono::seconds(20));
return 0;
}When to Use Processes vs. Threads
Processes provide isolation and fault tolerance; suitable for security‑critical or crash‑prone components.
Threads are lightweight, share address space, and have lower creation/termination overhead; ideal for fine‑grained parallelism and I/O‑bound workloads.
Process Lifecycle Management
Creation : system initialization, user request, or a running process calling fork() / exec().
Running : scheduler selects a ready process to execute.
Waiting : process blocks for I/O, resources, or events.
Ready : blocked process becomes runnable when its wait condition is satisfied.
Termination : normal exit, error exit, fatal error, or forced kill.
Process Suspension (Hanging)
When memory is needed, a process can be moved from RAM to swap (blocked or ready suspension). The OS may transition between:
Running → Blocked
Running → Ready
Ready → Running
Blocked → Ready
Process Scheduling Strategies
Different system types prioritize different metrics:
Batch systems – maximize throughput and turnaround time.
Interactive systems – minimize response time and ensure fairness.
Real‑time systems – meet hard or soft deadlines.
Thread Implementation
Two models exist:
User‑level threads – managed by a user‑space library; fast context switches but a blocking system call blocks the entire process.
Kernel‑level threads – managed by the OS kernel; each thread can be scheduled independently and a blocking call only blocks that thread.
Linux implements threads as lightweight processes created with the clone() system call, sharing selected resources (e.g., address space, file descriptors).
References
https://cloud.tencent.com/developer/article/1339562
https://blog.csdn.net/gatieme/article/details/51481863
https://blog.csdn.net/sddxqlrjxr/article/details/51249619
《Modern Operating Systems》
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.
Liangxu Linux
Liangxu, a self‑taught IT professional now working as a Linux development engineer at a Fortune 500 multinational, shares extensive Linux knowledge—fundamentals, applications, tools, plus Git, databases, Raspberry Pi, etc. (Reply “Linux” to receive essential resources.)
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.
