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

后端 未结 4 1027
梦毁少年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:16

    You could start the threads detached, and not worry about joining.

    for (int i = 0; i < 2; i++) {
        pthread_t tid;
        pthread_create(&tid, NULL, routine, NULL);
        pthread_detach(tid);
    }
    pthread_exit(0);
    

    Or, alternatively, you can have the thread that dies report back to the main thread who it is, so that the threads are joined in the order they exited, rather than in the order you created them in.

    void *routine(void *arg)
    {
        int *fds = (int *)arg;
        pthread_t t = pthread_self();
        usleep((rand()/(1.0 + RAND_MAX)) * 1000000);
        write(fds[1], &t, sizeof(t));
    }
    
    int main()
    {
        int fds[2];
        srand(time(0));
        pipe(fds);
        for (int i = 0; i < 2; i++) {
            pthread_t tid;
            pthread_create(&tid, NULL, routine, fds);
            printf("created: %llu\n", (unsigned long long)tid);
        }
        for (int i = 0; i < 2; i++) {
            pthread_t tid;
            read(fds[0], &tid, sizeof(tid));
            printf("joining: %llu\n", (unsigned long long)tid);
            pthread_join(tid, 0);
        }
        pthread_exit(0);
    }
    

提交回复
热议问题