• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 
2 #include <pthread.h>
3 #include <stdlib.h>
4 #include <unistd.h>
5 #include <assert.h>
6 /* Naive dining philosophers with inconsistent lock acquisition
7    ordering. */
8 
9 static pthread_t phil[5];
10 static struct {
11    pthread_mutex_t m;
12    char pad[120 - sizeof(pthread_mutex_t)];
13 } chop[5];
14 
dine(void * arg)15 void* dine ( void* arg )
16 {
17    int i;
18    long left = (long)arg;
19    long right = (left + 1) % 5;
20    for (i = 0; i < 1000/*arbitrary*/; i++) {
21       pthread_mutex_lock(&chop[left].m);
22       pthread_mutex_lock(&chop[right].m);
23       /* eating */
24       pthread_mutex_unlock(&chop[left].m);
25       pthread_mutex_unlock(&chop[right].m);
26    }
27    return NULL;
28 }
29 
main(void)30 int main ( void )
31 {
32    long i;
33    assert(sizeof(pthread_mutex_t) <= 120);
34 
35    for (i = 0; i < 5; i++)
36       pthread_mutex_init( &chop[i].m, NULL);
37 
38    for (i = 0; i < 5; i++)
39       pthread_create(&phil[i], NULL, dine, (void*)i );
40 
41    sleep(1);
42 
43    for (i = 0; i < 5; i++)
44       pthread_join(phil[i], NULL);
45 
46    return 0;
47 }
48