C++ 11:std::thread池化?

标签 c++ multithreading c++11 stdthread

在 C++03 中,我将 pthread 与一个自建线程池一起使用,该线程池始终保持几个线程运行(因为 pthread_create 很慢),这样我就可以启动小线程任务而不考虑性能问题。

现在,在 C++11 中,我们有了 std::thread。我想标准没有说明具体的实现,所以我的问题是关于标准库的实现。他们通常会选择一种池化方法,其中构造 std::threads 很便宜(例如,不会在 posix 上调用 pthread_create),还是会 std: :thread 只是一个包装器?

换句话说,C++11 中是否仍然推荐使用线程池,还是应该在需要时创建一个 std::thread 并将性能留给标准库?

最佳答案

通常,std::thread 应该是底层系统原语的最小包装。例如,如果你在 pthread 平台上,你可以用下面的程序测试,无论你创建多少线程,它们都是用唯一的 pthread_t ids 创建的(这意味着它们是动态创建的,而不是从线程池中借来的):

#include <assert.h>
#include <mutex>
#include <set>
#include <thread>
#include <vector>

#include <pthread.h>

int main() {
  std::vector<std::thread> workers;
  std::set<long long> thread_ids;
  std::mutex m;
  const int n = 1024;

  for (int i = 0; i < n; ++i) {
    workers.push_back(std::thread([&] {
      std::lock_guard<std::mutex> lock(m);
      thread_ids.insert(pthread_self());
    }));
  }
  for (auto& worker : workers) {
    worker.join();
  }
  assert(thread_ids.size() == n);

  return 0;
}

所以线程池仍然很有意义。也就是说,我看过一个视频,其中 C++ 委员会成员讨论了关于 std::async (IIRC) 的线程池,但我现在找不到。

关于C++ 11:std::thread池化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12993451/

相关文章:

c++ - C++0x 的 lambda 表达式没有命名类型是不是很糟糕?

c++ - 使用 cin 读取带有任意空格的逗号分隔整数对 (x,y)

c++ - 为什么派生类必须重新定义重写的基类方法

java - 如何创建一个等待 boolean 变量变为 true 的线程?

Python - 我应该使用线程还是进程来进行网络事件?

c++ - 如何在C++中获取正则表达式的底层字符串?

android - 在后台运行代码并验证线程

c++ - 我什么时候真的需要使用 atomic<bool> 而不是 bool?

c++ - 忽略 `gnu-zero-variadic-macro-arguments` 是否安全?

C++11 如何在其他类或源文件中引用类方法