C ++ 11:std :: thread池化了吗? [英] C++11: std::thread pooled?

查看:82
本文介绍了C ++ 11:std :: thread池化了吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

In C++03 I used pthread with a self-built thread pool that always kept a couple of threads running (since pthread_create is slow), this way I was able to launch threads for small tasks without thinking about performance issues.

现在,在C ++ 11中,我们有了std::thread.我猜该标准没有对特定实现做任何说明,所以我的问题是关于标准库实现.他们通常会选择一种构造std::thread便宜(例如,在posix上不调用pthread_create)的池化方法,还是std::thread只是包装器?

Now, in C++11 we have std::thread. I guess the standard doesn't say anything about the specific implementation, so my question is about the standard library implementations. Are they generally opting for a pooled approach where constructing std::threads is cheap (and e.g. doesn't call pthread_create on posix), or will std::thread just be a wrapper?

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

In other words, is a thread pool still recommended in C++11, or should I just create a std::thread whenever I need one and leave performance up to the standard library?

推荐答案

通常,std::thread应该是底层系统基元的最小包装.例如,如果您使用的是pthread平台,则可以使用以下程序进行测试,无论您创建了多少线程,它们都是使用唯一的pthread_t id创建的(这意味着它们是即时创建的,而不是从线程池中借来的):

Generally, std::thread should be a minimal wrapper around underlying system primitive. For example, if you're on pthread platform, you can test with the following program that no matter how many threads you create, they are all created with unique pthread_t ids (which implies they're created on the fly and not borrowed from a thread pool):

#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)的线程池,但是我现在找不到.

So thread pools still make perfect sense. That said, I've seen a video where C++ committee members discussed thread pools with regard to std::async (IIRC), but I can't find it right now.

这篇关于C ++ 11:std :: thread池化了吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆