Sobes.tech
Junior

What is the difference between a process and a thread in the context of operating systems?

sobes.tech AI

Answer from AI

Process — is a running program with its own address space, stack, open file descriptors, and other operating system resources. It is an isolated container for executing code.

Thread (or thread of execution) — is the smallest unit of execution within a process. A process can have one or multiple threads, which share the same address space and process resources, but each thread has its own call stack, program counter, and registers.

Main differences:

Attribute Process Thread
Address space Own, isolated Shares the process space
Resources Own set (files, memory, etc.) Shares process resources
Creation Costly process (resource copying) Relatively lightweight (requires fewer resources)
Context switch Long, requires switching address space Fast, occurs within the same process
Termination Terminating one process does not affect others Terminating a thread may affect other threads in the same process
Isolation High Low (vulnerable to errors of other threads)

Application:

  • Processes: used to run independent programs or services, where resource isolation and fault tolerance are required (e.g., launching a new application, web server).
  • Threads: used for executing parallel tasks within a single application, where work needs to be divided but shared data is important (e.g., background task execution, handling multiple web server requests within one process).

Example of creating a thread in C++ using pthreads:

#include <pthread.h>
#include <iostream>

void* thread_function(void* arg) {
    std::cout << "Hello from a thread!" << std::endl;
    pthread_exit(NULL);
}

int main() {
    pthread_t my_thread;
    int rc = pthread_create(&my_thread, NULL, thread_function, NULL);
    if (rc) {
        // Error handling
    }
    pthread_join(my_thread, NULL); // Wait for thread to finish
    return 0;
}