Skip to content

Processes & Threads ​

A process is a program loaded into memory and running, and a thread is the flow of execution that actually does the work inside that process. When a process is created, one thread (the main thread) is created along with it by default.

Analogy: A Restaurant ​

Process = the whole restaurant
┌─────────────────────────────────┐
│       Restaurant (Process)       │
│  ┌──────┐ ┌──────┐ ┌──────┐   │
│  │Waiter1│ │Waiter2│ │Waiter3│   │ ← threads
│  │Thread│ │Thread│ │Thread│   │
│  └──────┘ └──────┘ └──────┘   │
│                                 │
│ [Shared kitchen = shared memory (Heap)] │ ← all threads use the same Heap!
└─────────────────────────────────┘

The risk point in this document With MULTI_THREAD_ENABLE=True, several threads access the same Heap at the same time → the memory leak can progress faster

What Is Separate and What Is Shared ​

Each process gets its own independent address space from the operating system. Inside, it is divided as shown in Memory Layout.

  • Code: program instructions
  • Data: global variables, static variables (uninitialized ones go in the BSS segment)
  • Heap: data created during execution (malloc, new, Python objects, etc.)
  • Stack: local variables, parameters, return addresses

A thread has only its own Stack and registers (including the PC, which points to how far it has executed), and shares Code, Data and Heap with the other threads of the same process. For each thread to call different functions independently, the Stack that holds function call records and local variables must be separate.

text
Process A               Process B
┌──────────────┐        ┌──────────────┐
│ Code         │        │ Code         │
│ Data         │ cannot │ Data         │
│ Heap         │  see   │ Heap         │
│ Stack(thread1)│ each  │ Stack(thread1)│
│ Stack(thread2)│ other └──────────────┘
└──────────────┘
 Threads 1 and 2 share Code/Data/Heap

Trying it in Python shows the difference right away.

python
import threading
import multiprocessing

counter = 0  # global variable (Data segment)

def add_one():
    global counter
    counter += 1

if __name__ == "__main__":
    # Thread: inside the same process, so it shares the global variable
    t = threading.Thread(target=add_one)
    t.start(); t.join()
    print("After the thread runs, counter =", counter)

    # Process: has its own memory, so the child's change is not visible to the parent
    p = multiprocessing.Process(target=add_one)
    p.start(); p.join()
    print("After the process runs, counter =", counter)
text
After the thread runs, counter = 1
After the process runs, counter = 1

The value changed by the thread is visible in the main thread, so it became 1. The child process only changed the copy in its own memory, so the parent's value stays at 1. For processes to exchange data, they need a separate channel such as IPC.

Multiprocess vs Multithread ​

Multiprocessing splits one program into several processes that each work in parallel, and multithreading has several threads share the work inside one process.

ItemMultiprocessMultithread
MemorySeparate per processCode/Data/Heap shared, only Stack separate
SafetyIf one dies, the other processes are unaffected (the OS prevents memory intrusion)If one thread corrupts shared data, the whole process can stop
Resources · SpeedHeavy, since each has its own memory, and switching (context switching) is expensiveBecause they share, creating and switching are light and passing data is easy
Data sharingNeeds IPC (pipes, sockets, shared memory, etc.)Shared directly through global variables and the Heap
Watch out forCommunication cost, memory usageSynchronization (race conditions, deadlocks)
ExampleChrome runs a separate process per tabA web server handles each request with a thread

Why Context Switching Is Costly ​

One CPU runs only one flow at a time. To switch to another process, it must save the current state (registers, how far it has executed, etc.) to the PCB, then load and restore the next process's state. This is called context switching.

When switching between processes, the address space itself changes, so the cache and address translation info (TLB) become useless and have to be refilled, which is heavy work. Threads share the same address space, so this burden is much smaller. The detailed process is covered in PCB and Context Switching.

Multithreading's Weak Spot Is Guarded by Critical Sections ​

When several threads change the same data at once, the result can get tangled. This dangerous section of code is called a critical section, and it is protected by synchronizing so that these three conditions hold.

  • Mutual exclusion: while one thread is in the critical section, no other thread can enter
  • Progress: if the critical section is empty, one of the threads that want to enter must be able to enter
  • Bounded waiting: a thread waiting to enter must not wait forever

Concrete examples and tools to solve this continue in Race Conditions and Semaphores and Mutexes.

Extra Risks in a Multithreaded Environment ​

Thread 1: malloc(25MB) ──┐
Thread 2: malloc(25MB) ──┼──→ Concurrent Heap access
Thread 3: malloc(25MB) ──┘    (even more dangerous without synchronization!)

Why the warning message appeared:
"POTENTIAL DEADLOCK IN CONCURRENT MODE"
→ threads can freeze while waiting on each other's resources

Summary ​

ConceptPlain-language summary
ProcessA running program. Has its own memory space
ThreadA worker inside a process. Has only its own Stack and shares the rest with its coworkers
MultiprocessSafe but heavy, and needs IPC to exchange data
MultithreadLight and easy to share, but data gets tangled without synchronization
Context switchingSaving and restoring state when switching the flow of execution. Switching processes costs more
Critical sectionA section of code that multiple threads must not enter at the same time

In this document's exercise (B4-2), we confirmed the following.

  • A process is the whole restaurant, threads are the waiters inside it, and all threads use the same Heap (the shared kitchen).
  • With MULTI_THREAD_ENABLE=True, when several threads access the same Heap at once, the memory leak can progress faster.
  • Without synchronization it is even more dangerous, and threads can freeze while waiting on each other's resources ("POTENTIAL DEADLOCK IN CONCURRENT MODE").

Source: Codyssey-B1/B4-2