How to make main thread wait for all child threads finish?

后端 未结 4 1031
梦毁少年i
梦毁少年i 2020-12-01 17:56

I intend to fire 2 threads in the main thread, and the main thread should wait till all the 2 child threads finish, this is how I do it.

void *routine(void *         


        
4条回答
  •  星月不相逢
    2020-12-01 18:31

    First create all the threads, then join all of them:

    pthread_t tid[2];
    
    /// create all threads
    for (int i = 0; i < 2; i++) {
        pthread_create(&tid[i], NULL, routine, NULL);
    }
    
    /// wait all threads by joining them
    for (int i = 0; i < 2; i++) {
        pthread_join(tid[i], NULL);  
    }
    

    Alternatively, have some pthread_attr_t variable, use pthread_attr_init(3) then pthread_attr_setdetachedstate(3) on it, then pass its address to pthread_create(3) second argument. Thos would create the threads in detached state. Or use pthread_detach as explained in Jxh's answer.

提交回复
热议问题