Dining Philosophers Problem: C Implementation with Pthreads
Classified in Computers
Written at on English with a size of 2.22 KB.
C Implementation of the Dining Philosophers Problem
This program simulates the Dining Philosophers problem using C and Pthreads to demonstrate concurrency and synchronization concepts.
Global Variables
num_filosofos
(int): Number of philosophers.seed
(int): Seed for random number generation.holders
(pthread_mutex_t*): Array of mutexes representing forks.timeIni
(long): Initial time in milliseconds.
Functions
long dameTiempo()
Returns the current time in milliseconds.
int eat(int n)
Simulates a philosopher eating.
TimeWait
(long): Random wait time (0-500 ms).- Prints a message indicating the philosopher is eating.
- Waits for
TimeWait
milliseconds. - Releases the left and right forks (mutexes).
int sleep(int n)
Simulates a philosopher sleeping.
TimeWait
(long): Random wait time (0-500 ms).- Prints a message indicating the philosopher is sleeping.
- Waits for
TimeWait
milliseconds.
void* philosopher(void* arg)
Thread function for each philosopher.
n
(long): Philosopher's ID.- Continuously attempts to eat and sleep:
- Tries to acquire the left fork.
- If successful, tries to acquire the right fork.
- If both forks are acquired, calls
eat()
and thensleep()
. - If only one fork is acquired, releases it and calls
sleep()
. - If no forks are available, calls
sleep()
.
int main(int argc, char* argv[])
Main function of the program.
- Handles command-line arguments (not shown in the provided code).
- Prints the number of philosophers and the seed.
- Initializes
timeIni
with the current time. - Allocates memory for
forks
(mutex array). - Initializes each mutex in the
forks
array. - Creates a thread for each philosopher.
- Sleeps for 60 seconds before exiting.