sewardj | b411202 | 2007-11-09 22:49:28 +0000 | [diff] [blame^] | 1 | |
| 2 | #include <pthread.h> |
| 3 | #include <stdlib.h> |
| 4 | #include <unistd.h> |
| 5 | |
| 6 | /* Naive dining philosophers with inconsistent lock acquisition |
| 7 | ordering. */ |
| 8 | |
| 9 | static pthread_t phil[5]; |
| 10 | static pthread_mutex_t chop[5]; |
| 11 | |
| 12 | void* dine ( void* arg ) |
| 13 | { |
| 14 | int i; |
| 15 | long left = (long)arg; |
| 16 | long right = (left + 1) % 5; |
| 17 | for (i = 0; i < 1000/*arbitrary*/; i++) { |
| 18 | pthread_mutex_lock(&chop[left]); |
| 19 | pthread_mutex_lock(&chop[right]); |
| 20 | /* eating */ |
| 21 | pthread_mutex_unlock(&chop[left]); |
| 22 | pthread_mutex_unlock(&chop[right]); |
| 23 | } |
| 24 | return NULL; |
| 25 | } |
| 26 | |
| 27 | int main ( void ) |
| 28 | { |
| 29 | long i; |
| 30 | for (i = 0; i < 5; i++) |
| 31 | pthread_mutex_init( &chop[i], NULL); |
| 32 | |
| 33 | for (i = 0; i < 5; i++) |
| 34 | pthread_create(&phil[i], NULL, dine, (void*)i ); |
| 35 | |
| 36 | sleep(1); |
| 37 | |
| 38 | for (i = 0; i < 5; i++) |
| 39 | pthread_join(phil[i], NULL); |
| 40 | |
| 41 | return 0; |
| 42 | } |