/* cc thisfile.c -lthread -lpthread */
/*
*
This program demonstrate a potential deadlock scenario
* where two processes request the resources in a
* circular chain.
*
* Here a deadlock is not guaranteed to happen, but it has
* the potential.
*/
#include
#include
#include
#define NO_SHARE 0
void *work1(void *); /* thread routine */
void *work2(void *); /* thread routine */
int v = 0; /* global variable */
pthread_mutex_t first_mutex;
pthread_mutex_t second_mutex;
int main(int argc, char *argv[]) {
int i;
pthread_t tid[2];
printf("creating threads...\n");
pthread_mutex_init(&first_mutex, NULL);
pthread_mutex_init(&second_mutex, NULL);
pthread_create(&tid[0], NULL, work1, NULL);
pthread_create(&tid[1], NULL, work2, NULL);
printf("joining threads...\n");
pthread_join(tid[0], NULL);
pthread_join(tid[1], NULL);
return (0);
} /* main */
void * work1(void *arg) {
char c;
printf("in PID : %lu\n", pthread_self());
fflush(stdout);
pthread_mutex_lock(&first_mutex);
pthread_mutex_lock(&second_mutex);
v ++;
printf("PID : %lu my v is %d\n", pthread_self(), v);
fflush(stdout);
/*
printf("PID %lu Press to continue ...", pthread_self());
scanf("%c", &c);
*/
pthread_mutex_unlock(&second_mutex);
pthread_mutex_unlock(&first_mutex);
// pthread_exit(0);
}
void * work2(void *arg) {
char c;
printf("in PID : %lu\n", pthread_self());
fflush(stdout);
pthread_mutex_lock(&second_mutex);
pthread_mutex_lock(&first_mutex);
v ++;
printf("PID : %lu my v is %d\n", pthread_self(), v);
fflush(stdout);
/*
printf("PID %lu Press to continue ...", pthread_self());
scanf("%c", &c);
*/
pthread_mutex_unlock(&first_mutex);
pthread_mutex_unlock(&second_mutex);
// pthread_exit(0);
}