ThreadPool.h 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. /*
  2. * Copyright (c) 2016-present, Facebook, Inc.
  3. * All rights reserved.
  4. *
  5. * This source code is licensed under both the BSD-style license (found in the
  6. * LICENSE file in the root directory of this source tree) and the GPLv2 (found
  7. * in the COPYING file in the root directory of this source tree).
  8. */
  9. #pragma once
  10. #include "utils/WorkQueue.h"
  11. #include <cstddef>
  12. #include <functional>
  13. #include <thread>
  14. #include <vector>
  15. namespace pzstd {
  16. /// A simple thread pool that pulls tasks off its queue in FIFO order.
  17. class ThreadPool {
  18. std::vector<std::thread> threads_;
  19. WorkQueue<std::function<void()>> tasks_;
  20. public:
  21. /// Constructs a thread pool with `numThreads` threads.
  22. explicit ThreadPool(std::size_t numThreads) {
  23. threads_.reserve(numThreads);
  24. for (std::size_t i = 0; i < numThreads; ++i) {
  25. threads_.emplace_back([this] {
  26. std::function<void()> task;
  27. while (tasks_.pop(task)) {
  28. task();
  29. }
  30. });
  31. }
  32. }
  33. /// Finishes all tasks currently in the queue.
  34. ~ThreadPool() {
  35. tasks_.finish();
  36. for (auto& thread : threads_) {
  37. thread.join();
  38. }
  39. }
  40. /**
  41. * Adds `task` to the queue of tasks to execute. Since `task` is a
  42. * `std::function<>`, it cannot be a move only type. So any lambda passed must
  43. * not capture move only types (like `std::unique_ptr`).
  44. *
  45. * @param task The task to execute.
  46. */
  47. void add(std::function<void()> task) {
  48. tasks_.push(std::move(task));
  49. }
  50. };
  51. }