aboutsummaryrefslogtreecommitdiffstats
path: root/src/lib/utils/thread_utils/thread_pool.h
blob: 34f4f26dbc21b23634090c4796ef3ca2114ae34e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
/*
* (C) 2019 Jack Lloyd
*
* Botan is released under the Simplified BSD License (see license.txt)
*/

#ifndef BOTAN_THREAD_POOL_H_
#define BOTAN_THREAD_POOL_H_

#include <botan/types.h>
#include <functional>
#include <deque>
#include <vector>
#include <memory>
#include <utility>
#include <type_traits>
#include <mutex>
#include <thread>
#include <future>
#include <condition_variable>

namespace Botan {

class BOTAN_TEST_API Thread_Pool
   {
   public:
      /**
      * Return an instance to a shared thread pool
      */
      static Thread_Pool& global_instance();

      /**
      * Initialize a thread pool with some number of threads
      * @param pool_size number of threads in the pool, if 0
      *        then some default value is chosen
      */
      Thread_Pool(size_t pool_size = 0);

      ~Thread_Pool() { shutdown(); }

      void shutdown();

      size_t worker_count() const { return m_workers.size(); }

      Thread_Pool(const Thread_Pool&) = delete;
      Thread_Pool& operator=(const Thread_Pool&) = delete;

      Thread_Pool(Thread_Pool&&) = delete;
      Thread_Pool& operator=(Thread_Pool&&) = delete;

      /*
      * Enqueue some work
      */
      void queue_thunk(std::function<void ()>);

      template<class F, class... Args>
      auto run(F&& f, Args&&... args) -> std::future<typename std::result_of<F(Args...)>::type>
         {
         typedef typename std::result_of<F(Args...)>::type return_type;

         auto future_work = std::bind(std::forward<F>(f), std::forward<Args>(args)...);
         auto task = std::make_shared<std::packaged_task<return_type ()>>(future_work);
         auto future_result = task->get_future();
         queue_thunk([task]() { (*task)(); });
         return future_result;
         }

   private:
      void worker_thread();

      // Only touched in constructor and destructor
      std::vector<std::thread> m_workers;

      std::mutex m_mutex;
      std::condition_variable m_more_tasks;
      std::deque<std::function<void ()>> m_tasks;
      bool m_shutdown;
   };

}

#endif