Skip to content

Moabed21/Philosophers

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

40 Commits
Β 
Β 
Β 
Β 

Repository files navigation

This project has been created as part of the 42 curriculum by moabed

Description:

A simplified implementation of the classic Dining Philosophers Problem using Unix threads in C.
This project explores 🧡 threads, πŸ”’ synchronization, ⏱️ timing, and 🧠 memory concepts in a practical and visual way.


πŸ“š Table of Contents


🏠 Processes vs Threads

1️⃣ The Core Difference: Buildings vs. Roommates

🏠 The Process = The House

  • What is it? A standalone program running in memory.
  • Isolation: Fully independent. If one house burns down, the neighbor is safe.
  • Cost: Expensive to build (heavy system resources).
  • Privacy: Has its own private kitchen (Memory) and keys (Permissions).

πŸ‘― The Thread = The Roommates

  • What is it? A worker living inside the Process.
  • Sharing: Share the kitchen (Heap), living room (Global Variables), and bathroom (Files).
  • Risk: If one roommate causes a segfault πŸ’₯, the whole house crashes.

🀹 The CPU & Scheduling

How One CPU Runs Many Tasks

  • The Illusion: It looks like 10 apps are running at once.
  • Reality: The CPU is juggling.
    • Runs App A for 0.001 seconds
    • Switches to App B
    • Then back to App A

πŸ”„ Context Switch

The moment the CPU pauses one task to run another.

⚠️ Context switching costs time and energy (overhead).

πŸ‘” The Scheduler

The operating system's "Boss" that decides:

  • Who runs next
  • For how long
  • With what priority

πŸ“Œ Rule of Thumb

Concept Analogy
Concurrency One juggler handling 3 balls (time-slicing)
Parallelism Three jugglers, each with 1 ball (multi-core CPU)

🧬 Creating Life with fork()

When using fork(), you clone the current process.

  • πŸ‘¨ Parent β†’ The original
  • πŸ‘Ά Child β†’ The duplicate

Both continue execution from the same point.

Return Values:

  • 0 β†’ You're in the Child
  • PID β†’ You're in the Parent
  • -1 β†’ Error occurred

⚠️ Danger Zone: Zombies 🧟

If a child process finishes but the parent does not call wait() or waitpid():

  • The child becomes a Zombie process
  • It is dead, but still occupies system resources

πŸ—£οΈ Inter-Process Communication (IPC)

Processes are isolated, so they need special tools to communicate.

Method Analogy Speed Safety
Pipe Pneumatic tube πŸ“¦ Slower High
Shared Memory Shared whiteboard πŸ“ Very Fast Risky (Race conditions)

πŸ”‘ Synchronization & Semaphores

The Problem: Race Conditions 🏎️

Two threads try to modify the same variable at the same time.

Result?

  • Corrupted data
  • Unexpected behavior
  • Crashes

The Solution: Semaphore πŸ”‘

Think of it as a single-bathroom key.

wait() (Lock)

  • Is key available?
    • Yes β†’ Take it and enter.
    • No β†’ Wait outside.

post() (Unlock)

  • Leave bathroom.
  • Put key back.
  • Next waiting thread enters.

🧠 What Does "Atomic" Mean?

An atomic operation:

  • Happens in one indivisible step
  • Cannot be interrupted
  • Guarantees consistency

🧡 Unix Threads in C (pthread)

To use threads in C:

#include <pthread.h>

πŸ”Ή pthread_t

Used to define a thread:

pthread_t thread;

πŸ”Ή pthread_create()

Creates a new thread.

Prototype:

int pthread_create(pthread_t *thread, const pthread_attr_t *attr,
                   void *(*start_routine)(void*), void *arg);

Parameters:

  • Pointer to thread
  • Thread attributes
  • Function the thread will execute
  • Argument passed to the function

Return Value:

  • 0 β†’ Success
  • Non-zero β†’ Error code

πŸ”Ή pthread_join()

Waits for a thread to finish.

Prototype:

int pthread_join(pthread_t thread, void **retval);

Parameters:

  • Thread to wait for
  • Pointer to return value

Important ⚠️

Do NOT create and join the same thread inside the same loop iteration.

❌ That makes your program run sequentially
βœ… Create all threads first, then join them


⚠️ Race Conditions

A data race occurs when:

  • Two or more threads
  • Access shared memory
  • At the same time
  • And at least one modifies it

Result β†’ Undefined behavior.


πŸ”’ Mutexes

A mutex (Mutual Exclusion) prevents race conditions.

Functions:

  • pthread_mutex_t β†’ Declare mutex
  • pthread_mutex_init() β†’ Initialize
  • pthread_mutex_lock() β†’ Lock
  • pthread_mutex_unlock() β†’ Unlock
  • pthread_mutex_destroy() β†’ Destroy

Example:

pthread_mutex_t lock;

pthread_mutex_init(&lock, NULL);
pthread_mutex_lock(&lock);

/* Critical Section */

pthread_mutex_unlock(&lock);
pthread_mutex_destroy(&lock);

⏱️ Time Handling with gettimeofday()

Include:

#include <sys/time.h>

Example:

struct timeval current_time;

gettimeofday(&current_time, NULL);
printf("Current time (microseconds): %ld\n", current_time.tv_usec);
  • tv_sec β†’ Seconds
  • tv_usec β†’ Microseconds

Useful for:

  • Measuring philosopher eating time 🍝
  • Death timing ⏳
  • Logging events

🎯 Project Goal

This project demonstrates:

  • 🧠 Thread lifecycle management
  • πŸ”’ Proper synchronization
  • ⏱️ Time-based simulation
  • 🚫 Avoiding deadlocks
  • 🚦 Preventing race conditions

It is a simplified ("Lite") version of the Dining Philosophers problem designed to strengthen understanding of:

  • Concurrency
  • Parallelism
  • System-level programming
  • Resource sharing
  • CPU scheduling

πŸš€ Final Thoughts

Understanding threads and synchronization is fundamental for:

  • Operating Systems
  • High-performance servers
  • Real-time systems
  • Game engines
  • Embedded systems

Instructions:

1- compilation: run "make" in the philo directory to execute the code

2- execution: to run the program just type ./philo < number_of_philosophers > < time_to_die (in milliseconds) > < time_to_eat (in milliseconds) > < time_to_sleep (in milliseconds) >

< number_of_times_each_philosopher_must_eat (optional argument) > If all philosophers have eaten at least number_of_times_each_philosopher_must_eat times, the simulation stops. If not specified, the simulation stops when a philosopher dies.

Resources:

  1. Unix Threads in C : https://youtube.com/playlist?list=PLfqABt5AS4FmuQf70psXrsMLEDQXNkLq2&si=gpauzSCOB-1u4DzD

  2. The Dining Philosophers Problem : https://youtu.be/FYUi-u7UWgw?si=0zYeElF9Z37hYNKL

  3. 42-Philosophers : https://youtube.com/playlist?list=PLGU1kcPKHMKi41Py2kqxdvqYE3M9VhCHe&si=fp7ERBaJCK2Ym5zy

How AI was used:

I used AI in a logical way to help me in error handling , clarifying some concepts.

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published