如何使主线程等待所有子线程结束? [英] How to make main thread wait for all child threads finish?

查看:540
本文介绍了如何使主线程等待所有子线程结束?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我打算解雇2个线程在主线程,主线程必须等待,直到所有的2子线程完成,这是我要做的事。

 无效*例程(无效* ARG)
{
    睡眠(3);
}诠释的main()
{
    对(INT I = 0; I&2;我++){
        TID的pthread_t;
        在pthread_create(安培; TID,NULL,常规,NULL);
        在pthread_join(安培; TID,NULL); //这个函数会阻塞主线程,对不对?
    }
}

在上面的code,在pthread_join 的确让主线程等待子线程,但问题是,第二个线程不会的,直到创建第一个完成。这不是我想要的。

我要的是,2个线程都在主线程创建立刻,然后主线程等待他们完成。好像在pthread_join 不能做的伎俩,可以吗?

我想,也许通过信号灯我可以做的工作,但任何其他方式?


解决方案

  INT的main()
{
    的pthread_t TID [2];
    对(INT I = 0; I&2;我++){
        在pthread_create(安培; TID [Ⅰ],NULL,例程,NULL);
    }
    的for(int i = 0;我2;我++)
       在pthread_join(TID [I],NULL);
    返回0;
}

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 *arg)
{
    sleep(3);
}

int main()
{
    for (int i = 0; i < 2; i++) {
        pthread_t tid;
        pthread_create(&tid, NULL, routine, NULL);
        pthread_join(&tid, NULL);  //This function will block main thread, right?
    }
}

In the above code, pthread_join indeed makes main thread wait for the child threads, but the problem is, the second thread won't be created untill the first one finishes. This is not what I want.

What I want is, the 2 threads get created immediatly in the main thread, and then main thread waits for them to finish. Seems like pthread_join cannot do the trick, can it?

I thought, maybe via a semaphore I can do the job, but any other way?

解决方案

int main()
{
    pthread_t tid[2];
    for (int i = 0; i < 2; i++) {
        pthread_create(&tid[i], NULL, routine, NULL);
    }
    for (int i = 0; i < 2; i++)
       pthread_join(tid[i], NULL);
    return 0;
}

这篇关于如何使主线程等待所有子线程结束?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆