awesome-everything RU
↑ Back to the climb

Base CS from zero

Time and concurrency: code reading

Crux Read small snippets — an event-loop ordering puzzle, a thread interleaving, a lost-update data race, and a lock fix — and predict the behaviour or pick the correct fix.
Your altitude — climbing toward senior
ZeroJuniorMiddleSenior
You are at middle altitude — in the sky
◷ 14 min

Concurrency bugs are read in code and in traces of what ran when. Read each snippet, work out the order things actually happen, and pick what a careful engineer would conclude — or fix — first.

Goal

Practise the core skill of this unit: trace what runs when. Predict event-loop output order, spot how two threads can interleave on shared state, recognise a lost-update data race, and identify the lock that fixes it without overreaching.

Snippet 1 — event-loop ordering

console.log("start");

setTimeout(() => {
  console.log("timeout");   // a callback
}, 0);

console.log("end");
Quiz

What does this print, in order?

Snippet 2 — two threads, one shared variable

shared: total = 0

Thread A:                  Thread B:
  r = read(total)            r = read(total)   // both read 0
  r = r + 1                  r = r + 1
  write(total, r)            write(total, r)   // both write 1
Quiz

Both threads run this once, in parallel, on two cores. After both finish, what can total be — and what is this called?

Snippet 3 — the same code under load

total = 0
spawn 1000 threads, each does:  total = total + 1   // no synchronization
join all threads
print(total)
Quiz

On a multi-core machine, what is the likely printed value and why?

Snippet 4 — adding a lock

total = 0
lock = new Lock()

each of 1000 threads does:
  lock.acquire()
  total = total + 1     // protected: only one thread in here at a time
  lock.release()
Quiz

What does the lock change, and what is the cost?

Recap

Reading concurrency means reading when things run. The event loop puts synchronous code first and callbacks last (start, end, timeout). When work is split across threads that share state, a plain total = total + 1 is really read-add-write, so parallel threads can interleave, read the same value, and overwrite each other — a data race that loses updates and gives a wrong, nondeterministic total. A lock fixes it by making the shared section indivisible: one thread at a time, exact result restored. The cost is that the locked section runs serially. The senior move is to keep the lock for correctness and make the locked region as small as possible.

Continue the climb ↑Time and concurrency: reproduce and fix a race
shortcuts expand
search
K
prev piece
k
next piece
j
cycle tier
t
this menu
?
sources3
expand
  1. 01
  2. 02
  3. 03

Trademarks belong to their respective owners. Editorial reference only.