The Philosophers project aims to help us have a basic understanding of
- process synchronization and the sychronization between multiple threads of a single process,
- the problems related to the synchronization (ex. race condition - a situation where multiple threads or processes try to access shared data, deadlock)
- the solutions (Use of mutex or semaphore + Careful design of cooperation between threads/processes)
-
Mutex VS Semaphore
In the mandatory part, philosophers run as threads, so synchronization uses mutexes. A mutex is a simple binary lock used inside a single process: threads share the same memory, and the mutex ensures only one thread accesses a shared resource at a time.
In the bonus part, philosophers run as separate processes, which do not share memory. Because mutexes cannot synchronize across processes, the project uses semaphores instead. A semaphore is a kernel-managed shared counter. When initialized to N, it allows N processes to enter a critical section. Multiple processes can safetly decrement(sem_wait) and increment(sem_post) the same counter when occupying or releasing a resource. -
About race condition in bonus part: If you add
-fsanitize=thread -gto compile the program, TSan will report a race condition over variable "meal_time" between eat() and monitor_death(). However the meal_time is well protected by a semaphore. After some reseach online and discussion, it's possible that it's a false positive of TSan when semaphore is used. To further prove this possibility, I wrotetest.cwhich is a simple two-thread process with the shared variable well protected by semaphore, but TSan reports a race condition anyway. If you encounter the same problem and have some new findings, please feel free to leave me a message so that I can improve the bonus part. Thanks in advance! -
Useful links:
Process synchronization, its problems and solutions
Threads, mutex and programmation concurrency in C
Difference between process and thread
Mutex VS Semaphore