【问题标题】:boost::thread_group in C++11?C ++ 11中的boost :: thread_group?
【发布时间】:2012-04-11 06:19:09
【问题描述】:

C++11 中是否有类似boost::thread_group 的东西?

我只是想将我的程序从使用 boost:thread 移植到 C++11 线程,但找不到任何等效的东西。

【问题讨论】:

  • Boost 线程和 C++11 线程是不同的。我个人一直在使用 boost 线程,因为 API 更完整(以及当前缺乏线程本地存储的实现)。

标签: c++ boost c++11 boost-thread


【解决方案1】:

不,在 C++11 中没有直接等同于 boost::thread_group 的东西。如果你想要的只是一个容器,你可以使用std::vector<std::thread>。然后,您可以使用新的for 语法或std::for_each 在每个元素上调用join(),或其他任何方法。

【讨论】:

  • 自 2012 年以来有没有更好的解决方案来解决这个问题?
  • 我想补充一点,boost::thread_group 并没有什么魔力,它不仅仅是一个线程向量(“多一点”是一些实用函数,如 join_all 和 @ 987654328@).
【解决方案2】:

thread_group 没有进入 C++11、C++14、C++17 或 C++20 标准。

但解决方法很简单:

  std::vector<std::thread> grp;

  // to create threads
  grp.emplace_back(functor); // pass in the argument of std::thread()

  void join_all() {
    for (auto& thread : grp)
        thread.join();
  }

甚至不值得封装在一个类中(但肯定是可能的)。

【讨论】:

  • vector::emplace_back(functor) 的行为是否像 vector::push_back(std::move(functor));
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-05-16
  • 2015-01-28
  • 2013-10-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多