Interview Q&A · C · 12 questions in this topic

Processes, Threads & Synchronization — C Interview Q&A

All C topics

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

  1. 1Process — isolated memory, heavy, safe.
  2. 2Thread — shared memory, light, must synchronize.
  3. 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

Example.cc
#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

Example.cc
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.

Recommended resourcesAffiliate links · may earn us a commission

Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Cloud hosting for side projectsShip the portfolio project that gets you hired — free credits for new accounts.Claim credits