Process or thread: what changes for memory, crashes, and files?
Question
Your API server decodes user photos with a native C library. Sometimes a malformed file triggers a segmentation fault and aborts. You can run 4 decoders as threads inside the server, or as 4 separate worker processes.
- What happens to the API server if a decoder crashes in each setup?
- Which resources do threads share, and what stays private per thread?
- Why do teams still pick threads for trusted in-process work?
Show hints (3)
- "CRASH BLAST RADIUS"
When a native crash hits, the OS terminates one whole address space. Ask whether the API server lives inside that same space.
- "SHARED VERSUS PRIVATE"
Compare the heap, open sockets, and each call stack. Which ones can a sibling thread read or break directly?
- "COST OF ISOLATION"
Processes protect memory with separate page tables. What extra work does that add when workers share data or switch?
Show checked explanation
A thread crash kills the entire API server, while a worker process crash stops only that worker. Threads share the heap, globals, and open file descriptors, while keeping their own stack, registers, and thread-local state. Teams still pick threads for trusted work because direct shared memory avoids IPC copies and switches stay cheaper.
import multiprocessing as mp import os import threading def worker(items, fail=False): items.append("worker") if fail: os._exit(1) if __name__ == "__main__": t_items, p_items = ["main"], ["main"] t = threading.Thread(target=worker, args=(t_items,)) t.start() t.join() p = mp.Process(target=worker, args=(p_items, True)) p.start() p.join() print(f"thread={t_items} proc={p_items} exit={p.exitcode}")
thread=['main', 'worker'] proc=['main'] exit=1
Ran the process and thread isolation demo and shared-FD checks on CPython 3.12.10 (Windows x64). Checked by an editor other than the author.
Walkthrough
Look at what the output shows. The thread appended worker straight into t_items because both threads share one heap. The child process mutated its own copy, then called os._exit(1) like an abrupt crash. The parent kept running, kept p_items intact, and read exit=1.
| resource | separate processes | threads in one process |
|---|---|---|
| Address space (heap, globals) | Separate virtual memory | Shared |
| Call stack and CPU registers | Separate | Separate per thread |
| Open files and sockets | Separate descriptor tables | Shared table |
| Native crash (segfault, abort) | Kills one worker | Kills the whole server |
| Creation and context switch | Heavier: new page tables, TLB pressure | Lighter: same address space |
Isolate untrusted code in a process. A corrupt pointer in a C decoder can overwrite server memory or abort the whole process. Putting decoders in worker processes lets the supervisor detect the non-zero exit code, return an error for that one photo, and respawn the worker.
Use threads when workers trust each other. Threads read the same in-memory cache without copying bytes over pipes or sockets. Creating a thread skips setting up a new virtual address space, and switching between sibling threads stays in the same page-table context. The trade-off is that shared state needs synchronization so threads do not corrupt each other.
Common mistakes
- Thinking a
try/exceptblock catches a C segmentation fault in a thread. A segfault terminates the whole OS process immediately. - Assuming threads get their own open file table. If one thread closes a shared file descriptor, another thread's read fails or hits a reused descriptor.
- Claiming threads share a call stack. Every thread gets its own stack and register set so local variables and return addresses stay separate.
- Spawning processes for tiny sub-millisecond jobs. Process startup and IPC serialization can cost far more than the work itself.
Follow-up questions
- "How do separate worker processes pass image bytes back to the API server?" Over IPC: pipes, Unix domain sockets, loopback TCP, or shared memory (
mmap) paired with a small control message. Shared memory avoids copying multi-megabyte buffers while keeping the heap and crash domain separate. - "Isn't
fork()cheap on Linux because of copy-on-write?" At first, yes: the kernel shares read-only pages until either process writes to one. Heavy writes or garbage collection still trigger page faults and copies, and callingfork()inside a multithreaded process is error-prone because only the calling thread survives. - "What limits how many threads one process can spawn?" Each OS thread reserves its own stack (often 1 to 8 MiB of virtual space) plus kernel scheduling structures. Thousands of threads waste memory and scheduler time, which is why high-concurrency servers pair a small thread pool with async I/O.
What a strong answer covers
Maps each crash to its process isolation, separates shared heap and file descriptors from per-thread stacks, and weighs OS isolation against IPC and context-switch overhead.
Open in interactive practice deck →