【问题标题】:Is it safe to re-assign detached boost::thread重新分配分离的 boost::thread 是否安全
【发布时间】:2018-05-07 06:15:03
【问题描述】:

例如

boost::thread th = boost::thread(a_lengthy_function);
th.detach();
th = boost::thread(another_function);

第一个线程会被第二个线程取消或影响吗?

【问题讨论】:

  • 旁注:考虑使用std::thread
  • 考虑分离线程的作用。如果句柄仍然以某种方式影响分离的线程,那将是非常特殊的。

标签: c++ boost


【解决方案1】:

来自提升doc:

可以通过在 boost::thread 对象上显式调用 detach() 成员函数来分离线程。在这种情况下, boost::thread 对象不再代表现在分离的线程,而是代表 Not-a-Thread。

thread() noexcept;效果:构造一个 boost::thread 实例,引用 Not-a-Thread

所以分离的线程与默认构造的线程是一样的。所以,是的,您可以安全地移动分配给默认构造的线程,而第二个问题的答案是否定的,这两个线程完全不相关。

仅供参考,同样适用于 std::thread ...

【讨论】:

    【解决方案2】:

    这根本不重要。

    正如安德烈·卡隆所说:

    boost::thread 对象的生命周期和本机线程的生命周期无关。 boost::thread 对象可以随时超出范围。

    来自What’s the best way to delete boost::thread object right after its work is complete?

    【讨论】:

      猜你喜欢
      • 2021-12-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-29
      相关资源
      最近更新 更多