Carnegie Mellon
38
Avoiding Deadlock
int main(int argc, char** argv)
{
pthread_t tid[2];
Sem_init(&mutex[0], 0, 1); /* mutex[0] = 1 */
Sem_init(&mutex[1], 0, 1); /* mutex[1] = 1 */
Pthread_create(&tid[0], NULL, count, (void*) 0);
Pthread_create(&tid[1], NULL, count, (void*) 1);
Pthread_join(tid[0], NULL);
Pthread_join(tid[1], NULL);
printf("cnt=%d\n", cnt);
return 0;
}
void *count(void *vargp)
{
int i;
int id = (int) vargp;
for (i = 0; i < NITERS; i++) {
P(&mutex[0]); P(&mutex[1]);
cnt++;
V(&mutex[id]); V(&mutex[1-id]);
}
return NULL;
}
Acquire shared resources in same order
Tid[0]:
P(s
0
);
P(s
1
);
cnt++;
V(s
0
);
V(s
1
);
Tid[1]:
P(s
0
);
P(s
1
);
cnt++;
V(s
1
);
V(s
0
);