【问题标题】:What if thread exit before other thread wait for it(join)?如果线程在其他线程等待它(加入)之前退出怎么办?
【发布时间】:2016-08-15 09:55:23
【问题描述】:

例如,如果我创建 3 个线程并以相同的顺序加入它们。如果第二个线程先退出,那么 pthread_join 会发生什么。程序会阻塞直到 tid1 退出还是直接从 pthread_join(&tid2,NULL) 返回?

   pthread_t tid1,tid2,tid3;
   pthread_create(&tid1, NULL, SomeFun, NULL);
   pthread_create(&tid2, NULL, SomeFun, NULL);
   pthread_create(&tid3, NULL, SomeFun, NULL);
   pthread_join(&tid1, NULL);
   pthread_join(&tid2, NULL);
   pthread_join(&tid3, NULL);

【问题讨论】:

  • pthread_join() 不是可怕的“来自”。

标签: c multithreading unix pthreads pthread-join


【解决方案1】:

当你编码调用时:

pthread_join(&tid1, NULL);

如果tid1 尚未退出,则该调用将阻塞,直到退出。如果tid2 同时退出,则不会改变此特定调用的行为。但在那种情况下,当调用返回时,下一个调用:

pthread_join(&tid2, NULL);

将立即返回,因为tid2 已经退出。

如果您想在任意线程完成后立即执行某些工作,则需要使用 pthread_join() 以外的其他内容来与“某个线程已完成”事件同步。也许等待一个条件变量,每个线程在完成时都会发出信号(以及一些机制,例如队列,以便等待线程可以确定哪个线程已发出完成信号)。可以使用的另一种机制是让线程将信息写入管道,主(或控制)线程读取以获取该通知。

【讨论】:

    【解决方案2】:

    如果您加入一个已经结束的线程,pthread_join 将立即返回(并像往常一样销毁线程对象)。

    【讨论】:

    • 所以它会先执行pthread_join(&tid1,NULL)然后立即从pthread_join(&tid2,NULL)返回继续等待tid3?
    猜你喜欢
    • 2015-03-31
    • 1970-01-01
    • 1970-01-01
    • 2017-03-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多