Codexion
A multithreaded C simulation where N threads compete for shared resources without ever deadlocking or starving.
The problem
N coders sit around a table with N dongles, and each needs both neighbouring dongles to compile. Underneath, it’s the classic concurrency problem: one coordination mistake and every thread freezes, or one silently starves.
What I built
Each coder is a POSIX thread, and each dongle is a mutex with a condition variable. Waiting threads sleep instead of spinning. A min-heap I wrote from scratch picks who gets a freed dongle (first come, or closest to burnout), and a separate monitor thread stops the run the moment anyone burns out.
- Think
- Take both dongleseven threads go right first, odd go left
- Compile
- Debug & refactordongles back on the table
The thinking
The deadlock fix is asymmetry, not more locks. If every thread reaches left first, all of them can hold one dongle and wait forever. Making even threads reach right first breaks that cycle, so at least one thread always gets both.
What I learned
A thread asleep on a lock can’t notice its own deadline. Detection has to live outside the threads it watches. That’s why the monitor is its own thread with nothing else to do.
What I’d do differently
Timing uses gettimeofday, which jumps if the system clock is adjusted mid-run. I’d switch to CLOCK_MONOTONIC, and choose the scheduler at runtime instead of at compile time.
Numbers
~2 ms
average delay from burnout to detection
Measured by the monitor under the stress harness.
0
data races
ThreadSanitizer across thousands of stress-harness runs.
0 bytes
leaked at teardown
Valgrind, 0 errors.