Dining Philosophers Problem

# Dining Philosophers Problem -...

This preview shows pages 1–8. Sign up to view the full content.

Dining Philosophers Problem N Philosophers are in a round table. There is a fork in each side of a plate that they will use to it spaghetti. They need two forks to eat the spaghetti. They will have to share the forks with their neighbors.

This preview has intentionally blurred sections. Sign up to view the full version.

View Full Document
Dining Philosophers Problem Philosopher Spaghetti Fork
Dining Philosophers Problem Problem: They may all decide to grab the fork in their right at the same time and they will not be able to proceed. This is a deadlock

This preview has intentionally blurred sections. Sign up to view the full version.

View Full Document
Dining Philosophers Problem Philosopher holds fork Philosopher waits for fork
Dining Philosophers Problem (Unfixed Version) const int NPHILOSOPHERS=10; mutex_t fork_mutex[NPHILOSOPHERS]; pthread_t threadid[NPHILOSOPHERS]; void eat_spaghetti_thread(int i) { while (i_am_hungry[i]) { mutex_lock(&fork_mutex[i]); mutex_lock(&fork_mutex[(i+1)%NPHILOSOPHERS); // Eat spaghetti chomp_chomp(i); mutex_unlock(&fork_mutex[i]);

This preview has intentionally blurred sections. Sign up to view the full version.

View Full Document

This preview has intentionally blurred sections. Sign up to view the full version.

View Full Document
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: mutex_unlock(&fork_mutex[(i+1)%NPHILOSOPHERS); Dining Philosophers Problem (Unfixed Version) main() { for (int i = 0; i < NPHILOSOPHERS; i++) { mutex_init(&_fork_mutex[i]); } for (int i = 0; i < NPHILOSOPHERS; i++) { pthread_create(&threadid[i],eat_spaghetti_thread, i, NULL); } // Wait until they are done eating for (int i = 0; i < NPHILOSOPHERS; i++) { pthread_join(&threadid[i]); } Dining Philosophers Problem (Fixed Version) • The fork mutex have to be locked in order to prevent any deadlock. Condition Variables • Condition Variables is a mechanism used for synchronization like semaphores. • Condition variables and semaphores are equivalent in the sense that they can solve the same problems of synchronization • Condition variables are more expressive than semaphores but using one vs. the other is a matter of taste....
View Full Document

## This note was uploaded on 01/30/2012 for the course CS 252 taught by Professor Gustavorodriguez during the Fall '11 term at Purdue.

### Page1 / 8

Dining Philosophers Problem -...

This preview shows document pages 1 - 8. Sign up to view the full document.

View Full Document
Ask a homework question - tutors are online