Issue
I studied about pthread_join() I get to know that it run thread until thread processing is done, But in my case it is not working like this, I've to create 4 threads using 2 functions, I was expecting output as fun1,fun2,fun1 and fun2 again, because I'm calling threads in this sequence. Here is my code to describe my question more clearly.
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
void *thread1()
{
int c=0;
while(c++ < 10)
printf("%i : Hello!!\n",c);
}
void *thread2()
{
int c=0;
while(c++ < 10)
printf("%i : How Are You!!\n",c);
}
int main( int argc, char *argv[], char *env[] )
{
pthread_t tid1,tid2,tid3,tid4;
pthread_create(&tid1,NULL,thread1,NULL);
pthread_create(&tid2,NULL,thread2,NULL);
pthread_create(&tid3,NULL,thread1,NULL);
pthread_create(&tid4,NULL,thread2,NULL);
pthread_join(tid1,NULL);
pthread_join(tid2,NULL);
pthread_join(tid3,NULL);
pthread_join(tid4,NULL);
return 0;
}
Output variate every time, give different output every time, I don't understand whats happening. Output :
1 : Hello!!
2 : Hello!!
3 : Hello!!
4 : Hello!!
5 : Hello!!
6 : Hello!!
7 : Hello!!
1 : How Are You!!
1 : How Are You!!
2 : How Are You!!
3 : How Are You!!
4 : How Are You!!
8 : Hello!!
9 : Hello!!
10 : Hello!!
2 : How Are You!!
3 : How Are You!!
4 : How Are You!!
5 : How Are You!!
6 : How Are You!!
7 : How Are You!!
8 : How Are You!!
9 : How Are You!!
10 : How Are You!!
5 : How Are You!!
6 : How Are You!!
7 : How Are You!!
8 : How Are You!!
9 : How Are You!!
10 : How Are You!!
1 : Hello!!
2 : Hello!!
3 : Hello!!
4 : Hello!!
5 : Hello!!
6 : Hello!!
7 : Hello!!
8 : Hello!!
9 : Hello!!
10 : Hello!!
what I was expecting
1 : Hello!!
2 : Hello!!
3 : Hello!!
4 : Hello!!
5 : Hello!!
6 : Hello!!
7 : Hello!!
8 : Hello!!
9 : Hello!!
10 : Hello!!
1 : How Are You!!
2 : How Are You!!
3 : How Are You!!
4 : How Are You!!
5 : How Are You!!
6 : How Are You!!
7 : How Are You!!
8 : How Are You!!
9 : How Are You!!
10 : How Are You!!
1 : Hello!!
2 : Hello!!
3 : Hello!!
4 : Hello!!
5 : Hello!!
6 : Hello!!
7 : Hello!!
8 : Hello!!
9 : Hello!!
10 : Hello!!
1 : How Are You!!
2 : How Are You!!
3 : How Are You!!
4 : How Are You!!
5 : How Are You!!
6 : How Are You!!
7 : How Are You!!
8 : How Are You!!
9 : How Are You!!
10 : How Are You!!
Can anyone describe what's happening here ? Thanks!
Solution
I was expecting output as fun1,fun2,fun1 and fun2 again, because I'm calling threads in this sequence.
Threads aren't sequenced - they run independently. If you want the different threads to be synchronized or sequenced in any way, you have to code that yourself using things like mutexes, semaphores, condition variables, or some other explicit synchronization method.
You can't expect any particular execution order between separate threads without such explicit synchronization.
Answered By - Andrew Henle Answer Checked By - Robin (WPSolving Admin)