C++11 中的線程池 - Thread pooling in C++11

問題:

Relevant questions :相關問題

About C++11:關於 C++11:

About Boost:關於升壓:


How do I get a pool of threads to send tasks to , without creating and deleting them over and over again?如何獲得一個線程池將任務發送到,而無需一遍又一遍地創建和刪除它們? This means persistent threads to resynchronize without joining.這意味着持久線程無需加入即可重新同步。


I have code that looks like this:我有如下代碼:

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;
}

Instead of creating and joining threads each iteration, I'd prefer to send tasks to my worker threads each iteration and only create them once.我寧願每次迭代都將任務發送到我的工作線程,並且只創建一次,而不是每次迭代都創建和加入線程。


解決方案:

參考一: https://en.stackoom.com/question/145z9
參考二: https://stackoom.com/question/145z9
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章