0
#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

Steve Friedl
  • 3,929
  • 1
  • 23
  • 30
co_lin
  • 125
  • 7
  • Tip: `tid[0]` and `tid[1]` are preferable to `*tid` and `*(tid+1)`. – Barmar Nov 21 '20 at 13:54
  • 1
    The threads are killed when the process exits. If you don't wait for them with `pthread_join()`, the process exits right away. – Barmar Nov 21 '20 at 13:55
  • my bad :( thanks for the reply! it really helped – co_lin Nov 21 '20 at 14:01
  • 1
    Does this answer your question? [When to use pthread\_exit() and when to use pthread\_join() in Linux?](https://stackoverflow.com/questions/20824229/when-to-use-pthread-exit-and-when-to-use-pthread-join-in-linux) –  Nov 21 '20 at 14:04

1 Answers1

0

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.

Solomon Slow
  • 25,130
  • 5
  • 37
  • 57