My question is related to thread programming in C.
My problem is that I just want to create two threads in my main program. These two threads should work sequentially, which means my first thread should execute first (no other statement of any thread should be executed). First thread should have complete control. No other statement of any other thread, even main program statements, should be executed until the first thread is complete.
After completion of the first thread, the second thread should be executed in a similar way as the first.
After that my main should execute.
I know you can say why the hell I want to do this, because this thing can be achieved by just creating two functions and calling them in sequence, but for learning and for experimentation I want to do it with the help of threads.
I write some code in C as follows:
void* fun()
{
printf("\nThe thread 1 is running");
}
void* van()
{
printf("\nthread 2 is running ");
}
int main()
{
pthread_t t1,t2;
pthread_create(&t1,NULL,fun,NULL);
pthread_create(&t2,NULL,van,NULL);
printf("\nI'm in main\n");
pthread_join(t2,NULL);
}
The program is working perfectly but I don't understanding the working of the function pthread_join().
When I change my code a little bit as follows:
int main()
{
pthread_t t1,t2;
pthread_create(&t1,NULL,fun,NULL);
pthread_join(t2,NULL); // Change
pthread_create(&t2,NULL,van,NULL);
printf("\nI'm in main\n");
}
Now when I run the code it shows a segmentation fault.
Now my questions are the following:
- What is the attribute parameter in the
pthread_create()function? Why do we use them? What are the default attributes for a thread? Please explain with an example. - What is the argument in
pthread_create()function? Why we use them? What are the default arguments for a thread? Please explain with an example. - How does
pthread_join()work actually? What does it mean when my code callspthread_join()in main witht2as first argument. Does it mean main should suspend its execution until t2 execution has completed or something else? - What is the second argument in
pthread_join()? Why do we use it? What is its default value? Please explain with an example or code.
main()does not wait for thread 1 to complete before launching thread 2. If you waited for thread 1 to complete (pthread_join(&t1, NULL);after itspthread_create(), that would minimize the concurrent execution. Repeat for thread 2. Then you can run theprintf()inmain()itself. Since you've already waited for each thread to complete, you're done.