How can I wait for any/all pthreads to complete?

后端 未结 5 1430
深忆病人
深忆病人 2020-12-08 07:15

I just want my main thread to wait for any and all my (p)threads to complete before exiting.

The threads come and go a lot for different reasons, and I really don\'

5条回答
  •  -上瘾入骨i
    2020-12-08 07:33

    Do you want your main thread to do anything in particular after all the threads have completed?

    If not, you can have your main thread simply call pthread_exit() instead of returning (or calling exit()).

    If main() returns it implicitly calls (or behaves as if it called) exit(), which will terminate the process. However, if main() calls pthread_exit() instead of returning, that implicit call to exit() doesn't occur and the process won't immediately end - it'll end when all threads have terminated.

    • http://pubs.opengroup.org/onlinepubs/007908799/xsh/pthread_exit.html

    Can't get too much quick-n-dirtier.

    Here's a small example program that will let you see the difference. Pass -DUSE_PTHREAD_EXIT to the compiler to see the process wait for all threads to finish. Compile without that macro defined to see the process stop threads in their tracks.

    #include 
    #include 
    #include 
    #include 
    
    static
    void sleep(int ms)
    {
        struct timespec waittime;
    
        waittime.tv_sec = (ms / 1000);
        ms = ms % 1000;
        waittime.tv_nsec = ms * 1000 * 1000;
    
        nanosleep( &waittime, NULL);
    }
    
    void* threadfunc( void* c)
    {
        int id = (int) c;
        int i = 0;
    
        for (i = 0 ; i < 12; ++i) {
            printf( "thread %d, iteration %d\n", id, i);
            sleep(10);
        }
    
        return 0;
    }
    
    
    int main()
    {
        int i = 4;
    
        for (; i; --i) {
            pthread_t* tcb = malloc( sizeof(*tcb));
    
            pthread_create( tcb, NULL, threadfunc, (void*) i);
        }
    
        sleep(40);
    
    #ifdef USE_PTHREAD_EXIT
        pthread_exit(0);
    #endif
    
        return 0;
    }
    

提交回复
热议问题