Processes and threads
Program and process
A program is a file of instructions on disk. A process is a running copy of it, with its own memory and its own place in the code. Open the same app twice and you get one program but two processes. The OS gives each process a number, its process ID.
Process states
A process is in one of three states:
- Running: using the CPU right now.
- Ready: able to run, waiting for a turn on the CPU.
- Waiting (blocked): stuck until the disk or network answers.
When a waiting process gets its answer, it goes back to ready, not straight to running. A running process whose short time slice ends also goes back to ready, so others get a turn.
Context switch
One CPU core runs one process at a time. To swap, the OS does a context switch. It saves the running process's registers, the small fast storage inside the CPU. These include the program counter, which says where the next instruction is. Then it loads the next process's saved registers, and it carries on where it stopped. A switch takes time but does no useful work.
Threads
A thread is one path of execution inside a process. All threads of a process share its memory: the heap and global variables. Each thread has its own stack (for its function calls) and its own registers. Sharing is fast, but two threads changing the same data at once can lose an update.
Isolation
One process can't read or change another process's memory. The OS keeps them apart, so a crash in one stays in that one. To share data, they ask the OS for a pipe or a socket.
Remember
- Program = file on disk; process = running copy with its own memory.
- Ready, running, waiting; waiting goes back to ready.
- A context switch saves and loads registers, including the program counter.
- Threads share memory; each has its own stack and registers.
- Processes are kept apart and talk through the OS.