Interview Q&A · C · 12 questions in this topic
Processes, Threads & Synchronization — C Interview Q&A
Concurrent C — processes vs threads, pthreads, data races, mutexes, condition variables and atomics. Part of Processes & Threads · 202 questions in the C bank.
What is the difference between a process and a thread?
Answer
A process is an isolated address space with its own memory, file descriptors and at least one thread — crashes and leaks stay contained. Threads share the process address space: cheap to create and fast to communicate through shared memory, but one wild pointer or race corrupts everything.
Fork/exec for isolation and privilege separation; threads for shared-memory parallelism within a trust boundary.
Key points
- 1Process — isolated memory, heavy, safe.
- 2Thread — shared memory, light, must synchronize.
- 3Choose — isolation vs sharing cost.
How do you create threads with pthreads (create, join, detach)?
Answer
pthread_create launches with a start routine plus one void* argument (bundle more in a struct); pthread_join waits and collects the return pointer; pthread_detach releases for fire-and-forget. Every joinable thread must be joined or detached — leaking the choice leaks resources.
Pass heap or caller-owned structs as arguments, never stack addresses that may die first.
Example
#include <pthread.h> void *worker(void *arg) { /* ... */ return NULL; } /* pthread_t t; */ /* pthread_create(&t, NULL, worker, arg); */ /* pthread_join(t, NULL); */
What is a data race and why is it undefined behavior in C11?
Answer
A data race is two unsynchronized accesses to the same memory with at least one write. C11 made it undefined behavior — not merely a wrong value — so compilers may assume races never happen and optimize accordingly, making symptoms unreproducible.
Fix with mutexes for compound operations or _Atomic for single locations; ThreadSanitizer finds races empirically.
Example
int counter = 0; /* two threads: counter++ — data race (read-modify-write)! */ /* _Atomic int safe = 0; // atomic_inc: defined */
💡 Say undefined behavior, not just wrong answer — the UB framing is what interviewers check.
How do mutexes work (init, lock, unlock, destroy) and what are the pitfalls?
Answer
pthread_mutex_t serializes critical sections: init (or PTHREAD_MUTEX_INITIALIZER for statics), lock/unlock around shared access, destroy at teardown. Pitfalls: forgetting unlock on error paths (use cleanup handlers or single-exit), locking order inversions (deadlock), and holding locks across blocking calls.
Keep critical sections tiny, ordered globally, and never call unknown code (callbacks) while holding a lock.
Example
pthread_mutex_t m = PTHREAD_MUTEX_INITIALIZER; /* pthread_mutex_lock(&m); */ /* ... touch shared data ... */ /* pthread_mutex_unlock(&m); */
💡 Tiny, ordered, no-callbacks-under-lock is the mutex discipline trio.
What is a deadlock and how do you prevent it?
Answer
Deadlock is threads waiting on each other forever. Coffman conditions: mutual exclusion, hold-and-wait, no preemption, circular wait. Break any one: global lock ordering (breaks circular wait), trylock with backoff, or lock-free atomics for hot counters.
Consistent global lock ordering is the most practical prevention in real codebases.
Key points
- 1Mutual exclusion — resource cannot be shared.
- 2Hold-and-wait — holding one lock while wanting another.
- 3No preemption + circular wait — the fatal cycle.
What are condition variables and why must wait sit in a predicate loop?
Answer
pthread_cond_t lets threads sleep until shared state changes: waiters atomically release the mutex and sleep; signal/broadcast wake them. Spurious wakeups plus stolen notifications mean wait must re-check its condition in a while loop — always.
Mutate the shared state under the same mutex before signaling, and prefer broadcast when multiple waiters may proceed.
Example
/* waiter: */ /* pthread_mutex_lock(&m); */ /* while (!ready) pthread_cond_wait(&cv, &m); // predicate loop */ /* pthread_mutex_unlock(&m); */
What are C11 atomics (<stdatomic.h>) and what do they guarantee?
Answer
Atomics make single-location operations indivisible: loads, stores, fetch_add, exchange, compare_exchange run without torn reads or lost updates. They do not compose — two atomics updated together still race as a pair without a mutex.
Default sequential consistency is easiest to reason about; relaxed/acquire-release orderings are expert optimizations with weaker guarantees.
Example
#include <stdatomic.h> atomic_int hits = 0; /* atomic_fetch_add(&hits, 1); // atomic increment */
💡 Atomicity is per-location, not per-transaction — that boundary is the key insight.
What is the difference between mutex-based and lock-free synchronization?
Answer
Mutexes serialize whole critical sections: simple, composable, but blocking (contention, priority inversion, deadlock risk). Lock-free atomics make progress without locks: no blocking or deadlock, but only for carefully designed single-location protocols with ABA hazards and hard correctness proofs.
Guideline: mutexes by default; lock-free for measured hot paths using reviewed primitives.
What are `fork`, `exec` and `wait`? How do you launch a subprocess?
Answer
fork clones the process (child gets copies of memory/fds, return 0; parent gets the child pid); exec replaces the image with a new program; wait reaps the exit status (skipping it creates zombies). The fork+exec+wait trio is subprocess launching.
After fork, only async-signal-safe calls are safe before exec; stdio buffers duplicated across fork need fflush discipline.
Example
/* pid_t pid = fork(); */ /* if (pid == 0) { execlp("ls", "ls", NULL); _exit(127); } */ /* else { int status; waitpid(pid, &status, 0); } */
How do processes communicate (pipes, shared memory, signals)?
Answer
Pipes (anonymous for parent-child, FIFOs for named) stream bytes with kernel buffering. Shared memory (mmap/shm) shares regions at full speed — plus manual synchronization. Signals notify asynchronously (sigaction, flag-setting handlers only). Sockets/message queues add framing and networking.
Match the tool to the pattern: streams for pipelines, shm for bulk shared data, signals for notification only.
Key points
- 1Pipes — byte streams, kernel-buffered.
- 2Shared memory — fastest bulk, sync it yourself.
- 3Signals — notification, minimal handlers.
What is false sharing and how do you fix it?
Answer
False sharing is threads hammering different variables that share one cache line: every write invalidates the line for all cores, so performance collapses despite no logical sharing. Fix by padding/aligning hot per-thread data to cache-line boundaries (64 bytes typical) or accumulating thread-locally and merging at the end.
Symptom: scaling stalls at 2 threads on an embarrassingly parallel loop — profilers show coherence traffic, not lock contention.
Example
/* struct __attribute__((aligned(64))) slot { long value; }; */ /* // each thread: own cache line */
What tools detect threading bugs?
Answer
ThreadSanitizer (-fsanitize=thread) finds data races and lock-order issues at runtime; Helgrind/DRD do similar under valgrind with higher overhead. Static analyzers plus annotation discipline catch locking mistakes at compile time. Stress tests cover interleavings single runs miss.
Workflow: TSan in CI on stressed workloads, fix races — never ship a known race.
Example
/* gcc -std=c17 -fsanitize=thread -g main.c -o app_tsan -pthread */💡 TSan in CI on stressed workloads is the single highest-value threading practice.
Recommended resourcesAffiliate links · may earn us a commission