SkillGridLearn computer science by doing

Processes and threads

What a process actually is, how it differs from a thread, and what happens when the CPU switches between them.

11 min · 35 XP

A program on disk is just bytes. A process is that program running: its own memory, its own file descriptors, its own place in the CPU queue. Two copies of the same program are two separate processes that happen to share code.

A process is rarely simply "running". It is ready (waiting for CPU), running (on a core right now), or blocked (waiting for I/O or a lock). Most of a process's life is spent ready or blocked, not running.

ReadyRunningWaitingTerminatedscheduler picks itneeds I/OI/O donetime slice overexit()

The OS tracks each process with a process control block: its id, its state, where its memory starts, which files it has open, and the saved CPU registers. The PCB is the process, as far as the kernel is concerned.

/* PCB — то, что ОС помнит о процессе, пока он не на CPU. */
struct pcb {
  int   pid;             /* кто это                     */
  int   state;           /* READY / RUNNING / WAITING    */
  void *page_table;      /* где лежит его память        */
  struct regs saved;     /* PC, SP — где он остановился */
  int   open_files[16];  /* что он открыл               */
};

Practice

  1. Put the process states in the order a program typically moves through them.

    Hints
    • A process does not start running immediately after being created.
    • Waiting for a disk read is not the same as waiting for CPU.

    12 XP

  2. Two threads in one process increment the same counter without a lock. What is the most likely result?

    Hints
    • Think about what happens between reading the value and writing it back.
    • The scheduler can switch threads between any two instructions.

    12 XP

  3. Explain why a context switch is overhead, and when the OS is forced to pay it.

    Hints
    • Ask what useful work happens during the switch itself.
    • A blocking I/O call cannot keep the CPU.

    15 XP