Course contentsShow
← C
Lesson 1116 of 1,21915. Systems ProgrammingFree lesson

Threads vs Processes

Threads vs Processes

What you'll learn: The fundamental difference between a process and a thread and why we use threads for lightweight multitasking.

The Apartment Analogy

Imagine you are running a small catering business.

A Process is like a completely separate apartment building. Each building has its own plumbing, electricity, and kitchen. If you want to expand your business by renting a second building, you have a lot of privacy, but it’s very expensive to set up. If you need to move a tray of food from Building A to Building B, you have to physically leave, walk down the street, and knock on the door. In C, this is like using fork(); it creates a total copy of your program with its own isolated memory.

A Thread is like hiring an extra chef to work in your current kitchen. You are all in the same apartment, sharing the same fridge, the same stove, and the same pantry. It is much cheaper to hire a person than to rent a new building. Communication is instant—you just point at the salt. However, because you share the same space, you might bump into each other if you aren't careful.

Shared vs. Private Space

In systems programming, every process has its own private "address space" (memory). If Process A changes a global variable, Process B doesn't see it.

Threads are different. They live inside a process. While each thread has its own small "stack" to keep track of its current function calls, they all share the same "Heap" and "Global" memory.

#include <pthread.h>
#include <stdio.h>

// This variable is shared by all threads!
int shared_balance = 100;

void* add_money(void* arg) {
    shared_balance += 50;
    return NULL;
}

int main() {
    pthread_t thread_id;
    
    // Create a new thread (a new chef in our kitchen)
    pthread_create(&thread_id, NULL, add_money, NULL);
    
    // Wait for it to finish
    pthread_join(thread_id, NULL);
    
    // The main thread sees the change immediately
    printf("New balance: %d\n", shared_balance); // Prints 150
    return 0;
}

Why Choose Threads?

We use threads because they are "lightweight." Creating a thread is much faster for the Operating System than creating a process. Because they share memory, they can pass massive amounts of data to each other instantly without using complex networking tools. However, this power comes with a risk: if one thread crashes or accidentally overwrites shared data, it can take the whole process down with it.

Key takeaway

Processes are independent silos with their own memory, while threads are sibling workers that share the same memory for faster, cheaper communication.