#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
int count = 0;
pthread_mutex_t MUTEX = PTHREAD_MUTEX_INITIALIZER;
void* func1(void* a){
pthread_mutex_lock(&MUTEX);
for(;count < 4;count++){
printf("LOOP 1: %d\n",count);
sleep(1);
}
pthread_mutex_unlock(&MUTEX);
}
void* func2(void* a){
pthread_mutex_lock(&MUTEX);
for(;count < 8;count++){
printf("LOOP 2: %d\n",count);
sleep(1);
}
pthread_mutex_unlock(&MUTEX);
}
int main(){
pthread_t tid[2];
int a = 1;
int status;
if(pthread_create(tid,NULL,func1,(void*)&a))
printf("func1 error\n");
if(pthread_create(tid+1,NULL,func2,(void*)&a))
printf("func2 error\n");
//pthread_join(*tid, (void *) &status);
//pthread_join(*(tid+1), (void *) &status);
}
simple code for testing how thread and mutex works.
If I run the code, it just terminates without showing anything (sometimes just one line "LOOP 1: 0")
If I uncomment
//pthread_join(*tid, (void *) &status);
//pthread_join(*(tid+1), (void *) &status);
then it works well.
HOW this happens? someone please explain
pthread_join(t,...)
waits until the thread t
is finished. That is to say, the ...join
call does not return until t
is finished.
So, your question really is about what happens in a C program if the main()
function returns while threads that were created by pthread_create(...)
still are running.
The answer (at least, for some versions of C)* is that after main()
returns some value, v, the library then calls exit(v)
. You can look in the man pages or, in the documentation for whatever system you're running on to find out what else exit(...)
does, but one of the things that it does is, it terminates the entire process, including all of its threads.
* I am not 100% certain that every version of C and the C standard libraries behave in this way, but it's the behavior that I am accustomed to expect.
Note also that this behavior is different from modern C++ where, std::thread
instances can continue to run even after main(...)
has returned.