#include<stdio.h>
#include<string.h>
#include<pthread.h>
#include<stdlib.h>
#include<unistd.h>
#define NUM_THREADS 5
/* Global Declaration */
pthread_mutex_t lock;
int counter = 0;
void* trythis(void *arg)
{
unsigned long i = 0;
int *my_id = (int *)arg;
counter++;
printf("\n Thread %d Job %d has started\n", *my_id, counter);
if (counter == 5) {
printf("\n Thread %d Job %d trying to acquire the lock\n",
*my_id, counter);
}
pthread_mutex_lock(&lock);
int hang_cnt = 0;
do {
if (counter == 2) {
hang_cnt++;
printf("\n Thread %d Job %d inside while()- %d, and it is stuck in"
" func %s forever\n", *my_id, counter, hang_cnt, __func__);
} else {
printf("\n Thread %d Job %d in while loop in func %s\n",
*my_id, counter, __func__);
break;
}
} while (1); /* While loop */
pthread_mutex_unlock(&lock);
printf("\n Thread %d Job %d is able to return from func %s\n",
*my_id, counter, __func__);
return NULL;
}
int main(void)
{
int i = 0;
pthread_t tid[NUM_THREADS] = {0};
int error;
if (pthread_mutex_init(&lock, NULL) != 0) {
printf("\n mutex init has failed\n");
return 0;
}
while(i < NUM_THREADS) {
error = pthread_create(&(tid[i]), NULL, &trythis, (void *)&(tid[i]));
if (error != 0)
printf("\nThread can't be created : [%s]", strerror(error));
i++;
}
pthread_join(tid[0], NULL);
pthread_join(tid[1], NULL);
pthread_join(tid[2], NULL);
pthread_join(tid[3], NULL);
pthread_join(tid[4], NULL);
pthread_mutex_destroy(&lock);
return 0;
}