Pthreads multithreading problem of threads not terminating!!
by atharvdesai1996 from LinuxQuestions.org on (#5C8DY)
I wanted to print 1 to 10 for 3 threads. My code is able to do that but after that the program gets stuck. I tried using pthread_exit in the end of function. Also, I tried to remove while (1) in main and using pthread join there. But still, I got the same result. How should I terminate the threads?
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>
int done = 1;
//Thread function
void *foo()
{
for (int i = 0; i < 10; i++)
{
printf(" \n @@@@@@@@@@@@@");
pthread_mutex_lock(&lock);
if(done == 1)
{
done = 2;
printf (" \n %d", i);
pthread_cond_signal(&cond2);
pthread_cond_wait(&cond1, &lock);
printf (" \n Thread 1 woke up");
}
else if(done == 2)
{
printf (" \n %d", i);
done = 3;
pthread_cond_signal(&cond3);
pthread_cond_wait(&cond2, &lock);
printf (" \n Thread 2 woke up");
}
else
{
printf (" \n %d", i);
done = 1;
pthread_cond_signal(&cond1);
pthread_cond_wait(&cond3, &lock);
printf (" \n Thread 3 woke up");
}
pthread_mutex_unlock(&lock);
}
pthread_exit(NULL);
return NULL;
}
int main(void)
{
pthread_t tid1, tid2, tid3;
pthread_create(&tid1, NULL, foo, NULL);
pthread_create(&tid2, NULL, foo, NULL);
pthread_create(&tid3, NULL, foo, NULL);
while(1);
printf ("\n $$$$$$$$$$$$$$$$$$$$$$$$$$$");
return 0;
}


#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>
int done = 1;
//Thread function
void *foo()
{
for (int i = 0; i < 10; i++)
{
printf(" \n @@@@@@@@@@@@@");
pthread_mutex_lock(&lock);
if(done == 1)
{
done = 2;
printf (" \n %d", i);
pthread_cond_signal(&cond2);
pthread_cond_wait(&cond1, &lock);
printf (" \n Thread 1 woke up");
}
else if(done == 2)
{
printf (" \n %d", i);
done = 3;
pthread_cond_signal(&cond3);
pthread_cond_wait(&cond2, &lock);
printf (" \n Thread 2 woke up");
}
else
{
printf (" \n %d", i);
done = 1;
pthread_cond_signal(&cond1);
pthread_cond_wait(&cond3, &lock);
printf (" \n Thread 3 woke up");
}
pthread_mutex_unlock(&lock);
}
pthread_exit(NULL);
return NULL;
}
int main(void)
{
pthread_t tid1, tid2, tid3;
pthread_create(&tid1, NULL, foo, NULL);
pthread_create(&tid2, NULL, foo, NULL);
pthread_create(&tid3, NULL, foo, NULL);
while(1);
printf ("\n $$$$$$$$$$$$$$$$$$$$$$$$$$$");
return 0;
}