Fatih Çil

Self-Taught Developer

Software Engineer

Programmer

Game Developer

Fatih Çil

Self-Taught Developer

Software Engineer

Programmer

Game Developer

Blog Post

Philosophers: Dining With Threads and Mutexes

March 10, 2023 École 42

Hi! Philosophers is 42’s take on Dijkstra’s classic concurrency problem: N philosophers around a table, one fork between each pair, and everyone needs two forks to eat. If anyone starves, you fail.

The mandatory part: threads & mutexes

Each philosopher is a pthread, each fork a mutex. Sounds simple until you meet the classics: deadlock when everyone grabs their left fork at once, starvation when an unlucky philosopher never wins the race, and data races on the shared “last meal time” that a monitor thread reads while the owner writes. The fixes are textbook but you have to discover them yourself — asymmetric fork pickup, tight mutex scopes, and treating time-to-die checks with millisecond paranoia.

The bonus: processes & semaphores

The bonus rewrites everything with fork() and POSIX semaphores: forks become a counting semaphore, each philosopher its own process, and death monitoring happens with one watcher thread per process. Same problem, completely different toolbox — a great way to feel the difference between shared-memory and message-style concurrency.

Of everything at 42, this project changed my code the most: since Philosophers, I see every shared variable as a potential crime scene. Both versions are in my 42Cursus repository.

42 philosophers badge

Related Posts