C 11 中的线程池

新手上路,请多包涵

相关问题

关于 C++11:

关于升压:


如何获得一个 线程池将任务发送到,而无需一遍又一遍地创建和删除它们?这意味着持久线程无需加入即可重新同步。


我的代码如下所示:

 namespace {
  std::vector<std::thread> workers;

  int total = 4;
  int arr[4] = {0};

  void each_thread_does(int i) {
    arr[i] += 2;
  }
}

int main(int argc, char *argv[]) {
  for (int i = 0; i < 8; ++i) { // for 8 iterations,
    for (int j = 0; j < 4; ++j) {
      workers.push_back(std::thread(each_thread_does, j));
    }
    for (std::thread &t: workers) {
      if (t.joinable()) {
        t.join();
      }
    }
    arr[4] = std::min_element(arr, arr+4);
  }
  return 0;
}

与其在每次迭代中创建和加入线程,我更愿意在每次迭代时将任务发送到我的工作线程并且只创建一次。

原文由 Yktula 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 432
1 个回答

看起来线程池是非常流行的问题/练习:-)

我最近用现代 C++ 写了一个;它归我所有,可在此处公开获取 - https://github.com/yurir-dev/threadpool

它支持模板化的返回值、核心固定、某些任务的排序。两个 .h 文件中的所有实现。

所以,原来的问题是这样的:

 #include "tp/threadpool.h"

int arr[5] = { 0 };

concurency::threadPool<void> tp;
tp.start(std::thread::hardware_concurrency());

std::vector<std::future<void>> futures;
for (int i = 0; i < 8; ++i) { // for 8 iterations,
    for (int j = 0; j < 4; ++j) {
        futures.push_back(tp.push([&arr, j]() {
               arr[j] += 2;
            }));
    }
}

// wait until all pushed tasks are finished.
for (auto& f : futures)
    f.get();
// or just tp.end(); // will kill all the threads

arr[4] = *std::min_element(arr, arr + 4);

原文由 yurir 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题