【问题标题】:what happens if pthread_detach is called on a thread that's already returned如果在已经返回的线程上调用 pthread_detach 会发生什么
【发布时间】:2019-02-12 10:18:52
【问题描述】:

对于以下代码,如果创建的线程“thread_Id”在调用“pthread_detach(thread_Id)”之前返回/完成其工作“some_Function”,预期的行为是什么? “thread_Id”使用的资源会被释放吗?

pthread_create(&thread_Id, NULL, some_Function, &queue); ....

pthread_detach(thread_Id)

//没有pthread_join(thread_Id,...)

【问题讨论】:

  • 难以阅读。努力改进
  • 如果存在这种风险,最好使用pthread_attr_t * 而不是NULL,并设置线程属性,使线程处于分离状态。请参阅:pthread_attr_init()pthread_attr_setdetachstate()。我猜pthread_detach() 会报告失败并且线程状态可能不会被清理。 [...继续...]
  • [...continuation...] 但是,pthread_detach() 的规范说:pthread_detach() 函数应向实现表明线程线程的存储可以当该线程终止时被回收。如果线程没有终止,pthread_detach() 不会导致它终止。 但是,下面的基本原理是:如果实现在其生命周期结束后检测到线程 ID 的使用,建议该函数应该失败并报告 [ESRCH] 错误。 [...继续 2...]
  • [...continuation 2...] 这些基本原理暗示如果线程在可以分离之前终止,那么资源就会丢失(除非您决定pthread_join() ESRCH 失败时的线程 ID)。

标签: c linux pthreads


【解决方案1】:

在生命周期已结束的线程上调用pthread_detachundefined behaviour

如果应用程序尝试使用生命周期已结束的线程 ID,则行为未定义。"

recommendation 用于实现pthread_detach 是:

如果实现在其生命周期结束后检测到线程 ID 的使用,建议该函数失败并报告 [ESRCH] 错误。

【讨论】:

    【解决方案2】:

    是的,已经完成的线程资源将被自动释放。

    根据 Linux 的 pthread_detach() 手册,它失败的原因只有两个:

    EINVAL - thread is not a joinable thread.
    ESRCH  - No thread with the ID thread could be found.
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-01-13
      • 1970-01-01
      • 2019-04-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-07-24
      相关资源
      最近更新 更多