286 words
1 minute
Philosophers — Concurrency, Mutex Synchronization & Thread Safety in C
Philosophers — Concurrency & Deadlock Prevention
Philosophers explores thread synchronization and resource contention using POSIX threads and mutexes, modeling Edsger Dijkstra’s Dining Philosophers problem.
Synchronization Challenges
philosophers sit at a circular table with forks. Each philosopher requires both the left and right fork to eat:
[Philosopher 1] / \ (Fork 1) (Fork 2) / \ [Philosopher 5] [Philosopher 2] | | (Fork 5) (Fork 3) \ / [Philosopher 4] — (Fork 4) — [Philosopher 3]Potential Failure Modes
- Deadlock (Circular Wait): If all threads simultaneously lock their left fork, no thread can lock the right fork.
- Starvation: If a philosopher fails to acquire both forks before
time_to_dieexpires. - Data Races: Concurrent unsynchronized read/write operations on state variables (meal timestamps, stop flags).
Implementation Details
1. Asymmetric Locking Hierarchy
To break circular wait conditions, fork acquisition is ordered based on thread parity:
- Even ID philosophers lock their right fork first, then their left fork.
- Odd ID philosophers lock their left fork first, then their right fork.
- In addition, introducing a microsecond stagger on initial startup prevents initial lock stampedes.
void philo_take_forks(t_philo *philo){ if (philo->id % 2 == 0) { pthread_mutex_lock(philo->r_fork); philo_print(philo, "has taken a fork"); pthread_mutex_lock(philo->l_fork); philo_print(philo, "has taken a fork"); } else { pthread_mutex_lock(philo->l_fork); philo_print(philo, "has taken a fork"); pthread_mutex_lock(philo->r_fork); philo_print(philo, "has taken a fork"); }}2. Microsecond-Accurate Sleep Loop
Standard usleep() can introduce cumulative OS scheduler drift. A spin-check loop using gettimeofday() ensures accurate simulation timing:
void precise_usleep(long long duration_ms, t_table *table){ long long start;
start = get_current_time_ms(); while ((get_current_time_ms() - start) < duration_ms) { if (is_simulation_stopped(table)) break ; usleep(200); }}3. Monitoring Thread
A dedicated monitor thread polls last meal timestamps against time_to_die, setting a synchronized global shutdown flag if any thread starves.
Verification
- Verified clean under
ThreadSanitizer(-fsanitize=thread). - Verified free of thread race conditions and memory leaks with Valgrind Helgrind/DRD.
Sphynx | Ismail Larhrib