What is the difference between a process and a thread?

Process

A process is when a program loads into the memory, along with its required resources, and starts executing. In other words, it is a program in execution.

A process control block controls the process operations and contains critical information about the process such as the process ID, state, registers, counter, etc.

A process table maintains information about each process in the form of a context block to facilitate process scheduling and context switching.

Key points about a process

  • When a process is created, an address space is allocated to that process which contains the data segment, code segment, file segment, registers, stack, and heap.
  • Two processes cannot directly share information with each other. Inter-Process Communication (IPC) is used to facilitate communication.
  • A separate system call creates a single process.

Inter-process communication

Processes can communicate with each other via two methods:

  • Shared memory
  • Message passing

Shared memory

In shared memory, the process has access to a shared memory region. One process writes to that shared memory and the other processes can access or read information from the same memory region.

Message passing

In message passing, processes can read and write to a message queue without sharing any memory or variables. The messages are sent and received by processes through system calls.

Threads

A thread is a subset of a program, and a single program can have multiple threads. All the threads of a program share the same address space in memory.

Key points about a thread

  • A thread shares the file segment, code segment, data segment, and heap with the process that creates it, but each thread has its own stack and registers.
  • Threads of a single process can share information among each other.
  • A single system call can create multiple threads.

Inter-thread communication

Threads of the same process can communicate with each other through synchronization primitives like locks and semaphores, events like wait and notify, or through shared memory.

The following illustration shows how a process (single-threaded) and a multi-threaded process share memory.

The table below summarizes the differences between processes and threads.

Processes Threads
Processes are heavyweight Threads are lightweight
Each process has a separate memory space Each thread shares the memory with its parent process
Inter-process communication is slower Inter-thread communication is faster
Context switching takes more time Context switching takes less time
Processes do not share memory Threads share memory with other threads of the parent process
Copyright ©2024 Educative, Inc. All rights reserved