Interview questions can be tricky. In a highly stressful environment of a technical interview, coming up with a decent answer might be difficult. That’s why preparation is the key.

Today’s question:

What are the differences between a process and a thread?

A computer program is a set of instructions that can be executed by the CPU. Program is a static entity: it might be an executable file located somewhere in the file system. When you double-click the icon or run a command in the terminal, the program is loaded into RAM, and then it becomes a process.

A process is a program in execution. So, if you run a program multiple times, there will be a few processes running simultaneously, all corresponding to the same program.

Every process contains the program and some additional data needed to execute it - instruction pointer (pointer with the address of an instruction that will be executed next), it’s memory, CPU registers and other data (such as IO status information).

A photo of a thread. I'm extremely funny A photo of a thread. I’m extremely funny.

A process might contain a single or multiple threads of execution.

A Thread (or a thread of execution) is a sequence of instructions that can be processed by a single CPU core.

Imagine that you are planning a programming conference: you should create a plan of the event: who will be giving talks, what will they be about, etc. (that’s our program). The big day comes, guests arrive and our event is taking place (our process). During the conference, many talks (threads) might happen at the same time, in different parts of the venue.

Threads

In a multithreaded process, threads will share memory. All threads have individual call stacks and CPU registers, but data segment, heap, and code segment are shared. Thus, many threads can access and modify the same memory, which may lead to bugs that are very difficult to find. Processes don’t share memory in this way, they have to use inter-process communication instead.

TL;DR

  • A process is a program in execution. A thread is a sequence of program’s instructions that can be executed by a single CPU.
  • A process might create many threads. Those threads will share most of memory segments. Threads may access and modify shared memory. Processes use inter-process communication.