readme

201 lines 16 kB

This project has been created as part of the 42 curriculum by mleitao.

Description

Codexion is a concurrency simulation in C, modeled on the dining philosophers problem. A group of coders sits in a circle around a shared compiler. Between each pair of coders, there's a dongle. A coder needs both their right and left dongles at the same time to compile their code. After compiling, the coder puts both dongles back, debugs, refactors and immediately tries to compile again.

A coder who does not start a compile within time_to_burnout (ms measured from the start of the simulation or from the start of their last compile) burns out, which ends the simulation. The simulation also ends successfully once every coder has compiled number_of_compiles_required times.

Two rules set Codexion apart from the classic problem:

  • Dongle cooldown. A released dongle stays unavailable until dongle_cooldown milliseconds have passed, so a coder cannot immediately re-grab the dongle it just put down.
  • Explicit arbitration policy. When several coders want the same dongle, the winner is chosen by a scheduler passed on the command line: fifo (arrival order) or edf (earliest burnout deadline first). Each dongle owns a priority queue, implemented as a custom binary min-heap.

Each coder is one pthread. A separate monitor thread watches for burnout and for the compile quota being reached, and is the only thread that ends the simulation.

Instructions

Build

CommandDescription
make, make all, make codexionBuild the codexion binary
make cleanRemove the build/ directory
make fcleanRemove the build/ directory and the binary
make reFull rebuild (fclean + all)
make runBuild, then run with arguments set in config.mk
make leaksBuild, then run under valgrind --leak-check=full

Run

./codexion number_of_coders time_to_burnout time_to_compile time_to_debug \
           time_to_refactor number_of_compiles_required dongle_cooldown scheduler
ArgumentMeaning
number_of_codersNumber of coders, and also the number of dongles. Must be >= 1.
time_to_burnoutMilliseconds a coder may go without starting a compile before burning out.
time_to_compileMilliseconds spent compiling, holding both dongles.
time_to_debugMilliseconds spent debugging.
time_to_refactorMilliseconds spent refactoring, after which the coder immediately tries to compile again.
number_of_compiles_requiredOnce every coder reaches this count, the simulation stops.
dongle_cooldownMilliseconds a dongle stays unavailable after being released.
schedulerfifo or edf.

All eight arguments are mandatory. Negative values, non-integers, values above UINT_MAX, a zero coder count, and any scheduler other than fifo/edf are rejected with a message on stderr and exit code 1. Coders are numbered 1 to number_of_coders.

make run reads its arguments from config.mk, which is the quickest way to try a configuration without retyping the whole line.

Output

timestamp_in_ms X has taken a dongle
timestamp_in_ms X is compiling
timestamp_in_ms X is debugging
timestamp_in_ms X is refactoring
timestamp_in_ms X burned out

The timestamp is milliseconds since the start of the simulation. Every is compiling line is preceded by two has taken a dongle lines from the same coder. If a coder burns out, that line is the last line printed.

Examples

$ ./codexion 5 800 200 200 200 3 0 fifo     # completes, nobody burns out
$ ./codexion 4 410 200 200 0 20 0 edf       # completes under EDF arbitration
$ ./codexion 1 400 200 200 200 5 0 fifo     # one coder, one dongle: always burns out
$ ./codexion 4 310 200 100 100 100 0 fifo   # deadline too tight: a coder burns out
$ ./codexion 3 900 100 100 100 5 300 edf    # cooldown dominates the schedule

Blocking cases handled

Deadlock (circular wait)

The textbook failure of this problem is every coder grabbing their left dongle at once and then waiting forever for their right. Of Coffman's four conditions, three are inherent to the subject and cannot be removed:

  • Mutual exclusion — a dongle is held by at most one coder; this is the whole point of the exercise.
  • Hold and wait — a coder holds its first dongle while queuing for the second, because the subject requires two dongles held simultaneously.
  • No preemption — a dongle is never taken back from a coder mid-compile.

So the fourth condition, circular wait, is the one that gets broken, using a global resource ordering. Dongles are numbered 0..N-1, and take_dongles() always requests the lower-numbered dongle first, swapping the left/right pair when needed. Coder N is the one that actually swaps: its left dongle is N-1 and its right is 0, so it takes 0 first while everyone else takes their left. Since every thread acquires locks in ascending order, no cycle can form in the wait-for graph, and the system is deadlock-free by construction rather than by timeout or retry.

Dongle mutexes are also never nested with each other: dongle_acquire() takes one dongle's mutex, does its work, and releases it before the caller moves on to the next dongle. The only thing held across the second acquisition is the logical ownership flag held, not the mutex.

Starvation

Deadlock freedom alone does not stop one coder from being repeatedly beaten to a dongle by a faster neighbour. Every dongle therefore owns a priority queue (a custom binary min-heap) and grants itself only to the request at the top of that heap:

  • Under fifo, the key is a per-dongle ticket counter incremented on each request, so requests are served strictly in arrival order.
  • Under edf, the key is last_compile_start + time_to_burnout, the coder's burnout deadline, so the coder closest to burning out wins. Ties are broken by lower coder id, which makes the policy fully deterministic even when two deadlines land on the same millisecond. A coder that has never compiled has last_compile_start == 0, giving it the earliest possible deadline and therefore the highest priority.

A waiting coder is only ever blocked on a resource it can actually get: it pushes its request onto a dongle's heap at the moment it starts waiting for that dongle, and by then it already holds the lower-numbered one. So a queued request never sits behind a coder that is itself blocked elsewhere, and no priority inversion builds up.

Cooldown

A released dongle must stay untouchable for dongle_cooldown milliseconds. dongle_release() stamps release_ts with the release time, and can_take() refuses the dongle until release_ts + dongle_cooldown has elapsed. Dongles are initialised with release_ts = -dongle_cooldown so they are available at t = 0.

Waiting on a cooldown is not done by polling. When a coder is at the top of the heap and the dongle is free but still cooling down, wait_turn() uses pthread_cond_timedwait() with an absolute wake-up time of start_ms + release_ts + dongle_cooldown. The thread sleeps exactly as long as needed and wakes without burning CPU. In every other case it uses a plain pthread_cond_wait(), because only a release can change the outcome.

Precise burnout detection

A dedicated monitor thread polls every 500 µs. For each coder it reads last_compile_start under that coder's state_lock and compares last_compile_start + time_to_burnout against the current elapsed time. The 500 µs period keeps the reported burnout well inside the 10 ms budget required by the subject; measured error is under 1 ms.

Only the monitor decides that the simulation is over, so there is no race between several threads declaring different end conditions. It checks burnout first, then the compile quota, and stops on whichever fires.

Log serialisation and the last-line guarantee

Two things must hold: messages must never interleave, and nothing may be printed after a burnout.

The first is handled by log_lock, a mutex held across the whole printf. The second is handled by ordering: the monitor sets the stop flag before it takes log_lock to print the burnout line. Any coder that reaches log_state() afterwards acquires log_lock, re-reads the stop flag, sees the simulation is over, and prints nothing. A coder that got into log_state() first finishes its line and releases the lock before the monitor can print. Either way the burnout line is the last line. log_burnout() is the one function that prints unconditionally, since the subject requires the burnout message always to appear.

Shutdown without hanging

When the simulation ends, coders may be parked in pthread_cond_wait() with no release coming. After the monitor stops the run it calls wake_all(), which broadcasts on every dongle's condition variable. This cannot lose a wake-up: a coder checks the stop flag and calls pthread_cond_wait() while holding that dongle's mutex, and wake_all() needs the same mutex to broadcast. So either the broadcast happens after the coder is already inside cond_wait and reaches it, or it happens first, in which case the coder sees the stop flag before it can wait. Woken coders re-check the flag, remove their pending request from the heap, drop any dongle they still hold, and return. precise_sleep() polls the same flag, so sleeping coders exit early too.

The same path is reused by abort_run() when a pthread_create fails partway through startup: already-created threads are stopped, woken, and joined before the error is reported, so a failed launch leaves nothing running and nothing leaked.

Lock-order inversion

Two mutexes are ever held at the same time, and always in the same direction: log_lock is taken before stop_lock, never the reverse. sim_set_stop() releases stop_lock before log_burnout() reaches for log_lock, so the monitor never holds both in the opposite order. Dongle mutexes are leaf locks and are never held while taking another dongle mutex.

Degenerate configurations

  • One coder. With number_of_coders == 1 the coder's left and right dongle are the same one, so it can never compile. coder_routine() detects left == right, takes the single dongle, logs it, and parks until the monitor declares the inevitable burnout. Without this special case the coder would push the same request onto one heap twice and wait on itself.
  • Two coders. Both neighbours contend for both dongles; the ordering rule still applies and both take dongle 0 first.
  • Zero-length phases. time_to_compile, time_to_debug and time_to_refactor may all be 0; the phases collapse but the state lines are still printed in order.
  • Startup convoy. All coders would otherwise reach for their first dongle at the same instant. Even-numbered coders sleep for time_to_compile / 2 before their first acquisition, which staggers the ring and stops the initial waiting chain from forming.

Thread synchronization mechanisms

Threads

run_sim() records the simulation start time, then creates one thread per coder with pthread_create(), then one monitor thread. It joins all coder threads, then the monitor. Every thread receives a pointer to its own struct — a t_coder * for coders, the t_sim * for the monitor — so no shared state is passed through globals. The project uses no global variables at all.

pthread_mutex_t

Four kinds of mutex, each guarding a well-defined set of fields:

MutexProtectsHeld by
t_dongle.lockheld, ticket, release_ts and the dongle's request heapcoders, during acquire/release; the monitor, during wake_all()
t_coder.state_lockcompiles_done, last_compile_startthe owning coder when writing; the monitor when reading
t_sim.stop_lockthe stop flagevery thread, through sim_stopped() / sim_set_stop()
t_sim.log_lockstdoutany thread that prints

The dongle mutex is what makes a dongle impossible to duplicate. held is only ever read and written under it, and the check "is this dongle free and mine to take?" and the write held = 1 happen inside the same critical section, so two coders cannot both observe the dongle as free.

state_lock exists because compiles_done and last_compile_start are written by the coder thread and read by the monitor thread. Without it, the monitor could read a torn or stale deadline and either miss a burnout or invent one.

pthread_cond_t

Each dongle carries a condition variable, t_dongle.wait, used with that dongle's mutex. Waiting is done with the standard predicate loop rather than a single if, which makes spurious wake-ups harmless:

while (!sim_stopped(c->sim) && !can_take(c, d))
    wait_turn(c, d);

can_take() is the predicate: the dongle is not held, this coder is at the top of the dongle's heap, and the cooldown has expired. wait_turn() chooses between pthread_cond_timedwait() — when the only thing left to wait for is the cooldown, so the wake-up time is known exactly — and pthread_cond_wait() otherwise.

dongle_release() broadcasts rather than signals. Several coders can be queued on one dongle, and only the current heap top may proceed; a pthread_cond_signal() could wake a coder whose predicate is still false while leaving the eligible one asleep. Broadcasting wakes them all, each re-evaluates can_take(), and exactly one proceeds.

Race conditions

Two coders taking the same dongle. Prevented by making the test and the claim atomic: can_take() and d->held = 1 both execute while holding d->lock, so the window between checking and taking does not exist.

Monitor reading a half-updated deadline. do_compile() writes last_compile_start under state_lock; check_burnout() reads it under the same lock and copies it into a local before releasing. The comparison then runs on a stable snapshot.

Interleaved output. Every printf is wrapped in log_lock, and each message is a single printf ending in \n, so a line can never be split by another thread.

Printing after the simulation ended. The stop flag is read inside log_state() while log_lock is already held, which serialises "decide whether to print" with "print" and with the monitor's burnout line.

Lost wake-up on shutdown. Discussed above: the stop-flag check and the cond_wait happen under the dongle mutex that wake_all() must acquire, so the broadcast cannot slip between them.

Coder to monitor communication

Coders never talk to each other, as the subject requires. They publish two numbers under their own state_lock — when their last compile started, and how many compiles they have finished — and the monitor reads them. Nothing else flows in that direction.

The monitor talks back through exactly one bit, the stop flag behind stop_lock, reached only through sim_stopped() and sim_set_stop(). Coders check it at every loop boundary: before entering a phase, inside precise_sleep(), and inside the dongle acquisition loop. Combined with the wake_all() broadcast, one flag is enough to unwind every thread from any state it can be in.

Timing

now_ms() wraps gettimeofday(), which the subject recommends. Phase durations use precise_sleep(), which loops on usleep(200) and re-checks both the target time and the stop flag, rather than a single long usleep(). This keeps timestamps accurate and lets a sleeping coder react to the end of the simulation without waiting out its whole phase. ms_to_timespec() converts an absolute millisecond value into the struct timespec that pthread_cond_timedwait() expects; since both it and gettimeofday() are on CLOCK_REALTIME, the two clocks agree.

Resources

AI usage

Claude was used to:

  • Better understanding of POSIX threading concepts
  • Review the deadlock prevention strategy
  • Clarifying binary heap and EDF scheduler
  • Fix typos in this README
  1*This project has been created as part of the 42 curriculum by mleitao.*
  2
  3# Description
  4
  5Codexion is a concurrency simulation in C, modeled on the dining philosophers problem. A group of coders sits in a circle around a shared compiler. Between each pair of coders, there's a dongle. A coder needs both their right and left dongles at the same time to compile their code. After compiling, the coder puts both dongles back, debugs, refactors and immediately tries to compile again.
  6
  7A coder who does not start a compile within `time_to_burnout` (ms measured from the start of the simulation or from the start of their last compile) burns out, which ends the simulation. The simulation also ends successfully once every coder has compiled `number_of_compiles_required` times.
  8
  9Two rules set Codexion apart from the classic problem:
 10
 11- **Dongle cooldown.** A released dongle stays unavailable until `dongle_cooldown` milliseconds have passed, so a coder cannot immediately re-grab the dongle it just put down.
 12- **Explicit arbitration policy.** When several coders want the same dongle, the winner is chosen by a scheduler passed on the command line: `fifo` (arrival order) or `edf` (earliest burnout deadline first). Each dongle owns a priority queue, implemented as a custom binary min-heap.
 13
 14Each coder is one `pthread`. A separate monitor thread watches for burnout and for the compile quota being reached, and is the only thread that ends the simulation.
 15
 16# Instructions
 17
 18### Build
 19
 20Command | Description
 21--|--
 22`make`, `make all`, `make codexion` | Build the `codexion` binary
 23`make clean` |  Remove the `build/` directory
 24`make fclean` | Remove the `build/` directory and the binary
 25`make re` | Full rebuild (`fclean` + `all`)
 26`make run` | Build, then run with arguments set in `config.mk`
 27`make leaks` | Build, then run under `valgrind --leak-check=full`
 28
 29### Run
 30
 31```
 32./codexion number_of_coders time_to_burnout time_to_compile time_to_debug \
 33           time_to_refactor number_of_compiles_required dongle_cooldown scheduler
 34```
 35
 36Argument | Meaning
 37--|--
 38`number_of_coders` | Number of coders, and also the number of dongles. Must be `>= 1`.
 39`time_to_burnout` | Milliseconds a coder may go without *starting* a compile before burning out.
 40`time_to_compile` | Milliseconds spent compiling, holding both dongles.
 41`time_to_debug` | Milliseconds spent debugging.
 42`time_to_refactor` | Milliseconds spent refactoring, after which the coder immediately tries to compile again.
 43`number_of_compiles_required` | Once every coder reaches this count, the simulation stops.
 44`dongle_cooldown` | Milliseconds a dongle stays unavailable after being released.
 45`scheduler` | `fifo` or `edf`.
 46
 47All eight arguments are mandatory. Negative values, non-integers, values above `UINT_MAX`, a zero coder count, and any scheduler other than `fifo`/`edf` are rejected with a message on `stderr` and exit code `1`. Coders are numbered `1` to `number_of_coders`.
 48
 49`make run` reads its arguments from `config.mk`, which is the quickest way to try a configuration without retyping the whole line.
 50
 51### Output
 52
 53```
 54timestamp_in_ms X has taken a dongle
 55timestamp_in_ms X is compiling
 56timestamp_in_ms X is debugging
 57timestamp_in_ms X is refactoring
 58timestamp_in_ms X burned out
 59```
 60
 61The timestamp is milliseconds since the start of the simulation. Every `is compiling` line is preceded by two `has taken a dongle` lines from the same coder. If a coder burns out, that line is the last line printed.
 62
 63### Examples
 64
 65```
 66$ ./codexion 5 800 200 200 200 3 0 fifo     # completes, nobody burns out
 67$ ./codexion 4 410 200 200 0 20 0 edf       # completes under EDF arbitration
 68$ ./codexion 1 400 200 200 200 5 0 fifo     # one coder, one dongle: always burns out
 69$ ./codexion 4 310 200 100 100 100 0 fifo   # deadline too tight: a coder burns out
 70$ ./codexion 3 900 100 100 100 5 300 edf    # cooldown dominates the schedule
 71```
 72
 73# Blocking cases handled
 74
 75### Deadlock (circular wait)
 76
 77The textbook failure of this problem is every coder grabbing their left dongle at once and then waiting forever for their right. Of Coffman's four conditions, three are inherent to the subject and cannot be removed:
 78
 79- **Mutual exclusion** — a dongle is held by at most one coder; this is the whole point of the exercise.
 80- **Hold and wait** — a coder holds its first dongle while queuing for the second, because the subject requires two dongles held *simultaneously*.
 81- **No preemption** — a dongle is never taken back from a coder mid-compile.
 82
 83So the fourth condition, **circular wait**, is the one that gets broken, using a global resource ordering. Dongles are numbered `0..N-1`, and `take_dongles()` always requests the lower-numbered dongle first, swapping the left/right pair when needed. Coder `N` is the one that actually swaps: its left dongle is `N-1` and its right is `0`, so it takes `0` first while everyone else takes their left. Since every thread acquires locks in ascending order, no cycle can form in the wait-for graph, and the system is deadlock-free by construction rather than by timeout or retry.
 84
 85Dongle mutexes are also never nested with each other: `dongle_acquire()` takes one dongle's mutex, does its work, and releases it before the caller moves on to the next dongle. The only thing held across the second acquisition is the *logical* ownership flag `held`, not the mutex.
 86
 87### Starvation
 88
 89Deadlock freedom alone does not stop one coder from being repeatedly beaten to a dongle by a faster neighbour. Every dongle therefore owns a priority queue (a custom binary min-heap) and grants itself only to the request at the top of that heap:
 90
 91- Under `fifo`, the key is a per-dongle `ticket` counter incremented on each request, so requests are served strictly in arrival order.
 92- Under `edf`, the key is `last_compile_start + time_to_burnout`, the coder's burnout deadline, so the coder closest to burning out wins. Ties are broken by lower coder id, which makes the policy fully deterministic even when two deadlines land on the same millisecond. A coder that has never compiled has `last_compile_start == 0`, giving it the earliest possible deadline and therefore the highest priority.
 93
 94A waiting coder is only ever blocked on a resource it can actually get: it pushes its request onto a dongle's heap at the moment it starts waiting for *that* dongle, and by then it already holds the lower-numbered one. So a queued request never sits behind a coder that is itself blocked elsewhere, and no priority inversion builds up.
 95
 96### Cooldown
 97
 98A released dongle must stay untouchable for `dongle_cooldown` milliseconds. `dongle_release()` stamps `release_ts` with the release time, and `can_take()` refuses the dongle until `release_ts + dongle_cooldown` has elapsed. Dongles are initialised with `release_ts = -dongle_cooldown` so they are available at `t = 0`.
 99
100Waiting on a cooldown is not done by polling. When a coder is at the top of the heap and the dongle is free but still cooling down, `wait_turn()` uses `pthread_cond_timedwait()` with an absolute wake-up time of `start_ms + release_ts + dongle_cooldown`. The thread sleeps exactly as long as needed and wakes without burning CPU. In every other case it uses a plain `pthread_cond_wait()`, because only a release can change the outcome.
101
102### Precise burnout detection
103
104A dedicated monitor thread polls every 500 µs. For each coder it reads `last_compile_start` under that coder's `state_lock` and compares `last_compile_start + time_to_burnout` against the current elapsed time. The 500 µs period keeps the reported burnout well inside the 10 ms budget required by the subject; measured error is under 1 ms.
105
106Only the monitor decides that the simulation is over, so there is no race between several threads declaring different end conditions. It checks burnout first, then the compile quota, and stops on whichever fires.
107
108### Log serialisation and the last-line guarantee
109
110Two things must hold: messages must never interleave, and nothing may be printed after a burnout.
111
112The first is handled by `log_lock`, a mutex held across the whole `printf`. The second is handled by ordering: the monitor sets the stop flag *before* it takes `log_lock` to print the burnout line. Any coder that reaches `log_state()` afterwards acquires `log_lock`, re-reads the stop flag, sees the simulation is over, and prints nothing. A coder that got into `log_state()` first finishes its line and releases the lock before the monitor can print. Either way the burnout line is the last line. `log_burnout()` is the one function that prints unconditionally, since the subject requires the burnout message always to appear.
113
114### Shutdown without hanging
115
116When the simulation ends, coders may be parked in `pthread_cond_wait()` with no release coming. After the monitor stops the run it calls `wake_all()`, which broadcasts on every dongle's condition variable. This cannot lose a wake-up: a coder checks the stop flag and calls `pthread_cond_wait()` while holding that dongle's mutex, and `wake_all()` needs the same mutex to broadcast. So either the broadcast happens after the coder is already inside `cond_wait` and reaches it, or it happens first, in which case the coder sees the stop flag before it can wait. Woken coders re-check the flag, remove their pending request from the heap, drop any dongle they still hold, and return. `precise_sleep()` polls the same flag, so sleeping coders exit early too.
117
118The same path is reused by `abort_run()` when a `pthread_create` fails partway through startup: already-created threads are stopped, woken, and joined before the error is reported, so a failed launch leaves nothing running and nothing leaked.
119
120### Lock-order inversion
121
122Two mutexes are ever held at the same time, and always in the same direction: `log_lock` is taken before `stop_lock`, never the reverse. `sim_set_stop()` releases `stop_lock` before `log_burnout()` reaches for `log_lock`, so the monitor never holds both in the opposite order. Dongle mutexes are leaf locks and are never held while taking another dongle mutex.
123
124### Degenerate configurations
125
126- **One coder.** With `number_of_coders == 1` the coder's left and right dongle are the same one, so it can never compile. `coder_routine()` detects `left == right`, takes the single dongle, logs it, and parks until the monitor declares the inevitable burnout. Without this special case the coder would push the same request onto one heap twice and wait on itself.
127- **Two coders.** Both neighbours contend for both dongles; the ordering rule still applies and both take dongle `0` first.
128- **Zero-length phases.** `time_to_compile`, `time_to_debug` and `time_to_refactor` may all be `0`; the phases collapse but the state lines are still printed in order.
129- **Startup convoy.** All coders would otherwise reach for their first dongle at the same instant. Even-numbered coders sleep for `time_to_compile / 2` before their first acquisition, which staggers the ring and stops the initial waiting chain from forming.
130
131# Thread synchronization mechanisms
132
133### Threads
134
135`run_sim()` records the simulation start time, then creates one thread per coder with `pthread_create()`, then one monitor thread. It joins all coder threads, then the monitor. Every thread receives a pointer to its own struct — a `t_coder *` for coders, the `t_sim *` for the monitor — so no shared state is passed through globals. The project uses no global variables at all.
136
137### `pthread_mutex_t`
138
139Four kinds of mutex, each guarding a well-defined set of fields:
140
141Mutex | Protects | Held by
142--|--|--
143`t_dongle.lock` | `held`, `ticket`, `release_ts` and the dongle's request heap | coders, during acquire/release; the monitor, during `wake_all()`
144`t_coder.state_lock` | `compiles_done`, `last_compile_start` | the owning coder when writing; the monitor when reading
145`t_sim.stop_lock` | the `stop` flag | every thread, through `sim_stopped()` / `sim_set_stop()`
146`t_sim.log_lock` | `stdout` | any thread that prints
147
148The dongle mutex is what makes a dongle impossible to duplicate. `held` is only ever read and written under it, and the check "is this dongle free and mine to take?" and the write `held = 1` happen inside the same critical section, so two coders cannot both observe the dongle as free.
149
150`state_lock` exists because `compiles_done` and `last_compile_start` are written by the coder thread and read by the monitor thread. Without it, the monitor could read a torn or stale deadline and either miss a burnout or invent one.
151
152### `pthread_cond_t`
153
154Each dongle carries a condition variable, `t_dongle.wait`, used with that dongle's mutex. Waiting is done with the standard predicate loop rather than a single `if`, which makes spurious wake-ups harmless:
155
156```c
157while (!sim_stopped(c->sim) && !can_take(c, d))
158    wait_turn(c, d);
159```
160
161`can_take()` is the predicate: the dongle is not held, this coder is at the top of the dongle's heap, and the cooldown has expired. `wait_turn()` chooses between `pthread_cond_timedwait()` — when the only thing left to wait for is the cooldown, so the wake-up time is known exactly — and `pthread_cond_wait()` otherwise.
162
163`dongle_release()` broadcasts rather than signals. Several coders can be queued on one dongle, and only the current heap top may proceed; a `pthread_cond_signal()` could wake a coder whose predicate is still false while leaving the eligible one asleep. Broadcasting wakes them all, each re-evaluates `can_take()`, and exactly one proceeds.
164
165### Race conditions
166
167**Two coders taking the same dongle.** Prevented by making the test and the claim atomic: `can_take()` and `d->held = 1` both execute while holding `d->lock`, so the window between checking and taking does not exist.
168
169**Monitor reading a half-updated deadline.** `do_compile()` writes `last_compile_start` under `state_lock`; `check_burnout()` reads it under the same lock and copies it into a local before releasing. The comparison then runs on a stable snapshot.
170
171**Interleaved output.** Every `printf` is wrapped in `log_lock`, and each message is a single `printf` ending in `\n`, so a line can never be split by another thread.
172
173**Printing after the simulation ended.** The stop flag is read inside `log_state()` while `log_lock` is already held, which serialises "decide whether to print" with "print" and with the monitor's burnout line.
174
175**Lost wake-up on shutdown.** Discussed above: the stop-flag check and the `cond_wait` happen under the dongle mutex that `wake_all()` must acquire, so the broadcast cannot slip between them.
176
177### Coder to monitor communication
178
179Coders never talk to each other, as the subject requires. They publish two numbers under their own `state_lock` — when their last compile started, and how many compiles they have finished — and the monitor reads them. Nothing else flows in that direction.
180
181The monitor talks back through exactly one bit, the `stop` flag behind `stop_lock`, reached only through `sim_stopped()` and `sim_set_stop()`. Coders check it at every loop boundary: before entering a phase, inside `precise_sleep()`, and inside the dongle acquisition loop. Combined with the `wake_all()` broadcast, one flag is enough to unwind every thread from any state it can be in.
182
183### Timing
184
185`now_ms()` wraps `gettimeofday()`, which the subject recommends. Phase durations use `precise_sleep()`, which loops on `usleep(200)` and re-checks both the target time and the stop flag, rather than a single long `usleep()`. This keeps timestamps accurate and lets a sleeping coder react to the end of the simulation without waiting out its whole phase. `ms_to_timespec()` converts an absolute millisecond value into the `struct timespec` that `pthread_cond_timedwait()` expects; since both it and `gettimeofday()` are on `CLOCK_REALTIME`, the two clocks agree.
186
187# Resources
188
189- [POSIX Threads Programming - Lawrence Livermore National Laboratory](https://hpc-tutorials.llnl.gov/posix/)
190- [Dining philosophers problem – Wikipedia](https://en.wikipedia.org/wiki/Dining_philosophers_problem)
191- `pthread_*` man pages
192- [Earliest deadline first scheduling - Wikipedia](https://en.wikipedia.org/wiki/Earliest_deadline_first_scheduling)
193- [Binary heap - Wikipedia](https://en.wikipedia.org/wiki/Binary_heap)
194
195### AI usage
196
197Claude was used to:
198- Better understanding of POSIX threading concepts
199- Review the deadlock prevention strategy
200- Clarifying binary heap and EDF scheduler
201- Fix typos in this README