Master the fundamental concepts of threads & concurrency through this focused micro-challenge.
Cooperative threads fail when one thread never yields. Preemption fixes that by forcing switches on asynchronous events. In userspace you can hijack SIGALRM from setitimer to run a scheduler on every tick.
Setup sequence:
SIGALRM handler that calls schedule()setitimer(ITIMER_REAL, ...) for quantumFor example, a 10 ms timer firing while thread A runs in an infinite loop preempts A, saves its context, and dispatches thread B without A calling yield().
This is how early user-level threading libraries like GNU Pth added preemption on top of cooperative scheduling, and the async-signal-safety constraint you'll hit is a real, frequently-violated rule: calling malloc() or printf() inside a signal handler is a documented source of deadlocks and heap corruption in production C code, which is exactly why POSIX maintains an explicit async-signal-safe function list.
Before you call the implementation done, walk failure modes on purpose. Test empty structures, single-element edge cases, maximum concurrency, and errno paths that must not crash the program. OS code usually fails in production when happy-path tests pass but invariants break under contention or memory pressure.
Keep structures small and name fields after kernel counterparts when possible. That lets you read man pages and kernel source side by side while you work. Print observable events during development; remove noisy logs once tests pass reliably.
You will wire alarm-driven preemption into your green-thread runtime. The task asks you to compare cooperative-only and preemptive modes on a CPU-bound loop so the starvation difference is visible.
Implement preemptive scheduling for green threads using SIGALRM.
Requirements:
Test Scenarios:
Three hints are available for this task, revealed one at a time inside the code workspace so you can struggle productively before seeing them.
All starter code and reference implementations are available for your local setup.
View on Github