Whetstone
0day streak

Concurrency in Application Code

Races, locks, and why async is not the same as parallel.

14

Questions

6/3/5

Easy / Med / Hard

Your accuracy

Concurrency is about a program making progress on several things; parallelism is about doing them at literally the same instant. A single-threaded event loop is concurrent and not parallel, which is why one blocking call stalls everything.

A race condition is when the result depends on timing. The classic is read-modify-write: two requests read a balance of 100, both subtract 10, both write 90, and one withdrawal vanished. Nothing crashed and the data is now wrong — which is what makes races so unpleasant to find.

A critical section is the code that must not run concurrently. A mutex enforces one holder at a time; a semaphore allows up to N, which is how connection pools bound concurrency.

Deadlock needs four conditions together: mutual exclusion, hold-and-wait, no preemption, and circular wait. Break any one and it cannot happen — which is why "always acquire locks in the same order" works, since it removes circular wait. Livelock is subtler: threads keep responding to each other and none makes progress.

Optimistic versus pessimistic locking. Pessimistic takes the lock up front and blocks others. Optimistic assumes conflict is rare, does the work, and checks at write time — usually with a version column — retrying if something changed underneath. Optimistic wins when contention is low, which is most of the time.

Async/await is not concurrency by itself. It is a way to write non-blocking code readably. Awaiting sequentially in a loop is as slow as blocking; the gain comes from starting work then awaiting together. And a CPU-bound loop blocks an event loop completely, because there is no yield point.

Immutability is the cheapest concurrency strategy available. Data that cannot change needs no lock, which is why functional approaches scale across threads so easily.

Idempotency matters here too: with retries in the picture, an operation that is safe to apply twice removes an entire category of concurrency bug.