Botan 2.19.5 Crypto and TLS for C&

thread_pool.h
Go to the documentation of this file.
1/*
2* (C) 2019 Jack Lloyd
3*
4* Botan is released under the Simplified BSD License (see license.txt)
5*/
6
7#ifndef BOTAN_THREAD_POOL_H_
8#define BOTAN_THREAD_POOL_H_
9
10#include <botan/types.h>
11#include <functional>
12#include <deque>
13#include <vector>
14#include <memory>
15#include <utility>
16#include <type_traits>
17#include <mutex>
18#include <thread>
19#include <future>
20#include <condition_variable>
21
22 namespace Botan {
23
24 class BOTAN_TEST_API Thread_Pool
25 {
26 public:
27 /**
28 * Return an instance to a shared thread pool
29 */
30 static Thread_Pool& global_instance();
31
32 /**
33 * Initialize a thread pool with some number of threads
34 * @param pool_size number of threads in the pool, if 0
35 * then some default value is chosen
36 */
37 Thread_Pool(size_t pool_size = 0);
38
39 ~Thread_Pool() { shutdown(); }
40
41 void shutdown();
42
43 size_t worker_count() const { return m_workers.size(); }
44
45 Thread_Pool(const Thread_Pool&) = delete;
46 Thread_Pool& operator=(const Thread_Pool&) = delete;
47
48 Thread_Pool(Thread_Pool&&) = delete;
49 Thread_Pool& operator=(Thread_Pool&&) = delete;
50
51 /*
52 * Enqueue some work
53 */
54 void queue_thunk(std::function<void ()>);
55
56 template<class F, class... Args>
57 auto run(F&& f, Args&&... args) -> std::future<typename std::result_of<F(Args...)>::type>
58 {
59 typedef typename std::result_of<F(Args...)>::type return_type;
60
61 auto future_work = std::bind(std::forward<F>(f), std::forward<Args>(args)...);
62 auto task = std::make_shared<std::packaged_task<return_type ()>>(future_work);
63 auto future_result = task->get_future();
64 queue_thunk([task]() { (*task)(); });
65 return future_result;
66 }
67
68 private:
69 void worker_thread();
70
71 // Only touched in constructor and destructor
72 std::vector<std::thread> m_workers;
73
74 std::mutex m_mutex;
75 std::condition_variable m_more_tasks;
76 std::deque<std::function<void ()>> m_tasks;
77 bool m_shutdown;
78 };
79
80}
81
82#endif
Botan::Thread_Pool
Definition: thread_pool.h:25
Botan::Thread_Pool::Thread_Pool
Thread_Pool(Thread_Pool &&)=delete
Botan::Thread_Pool::worker_count
size_t worker_count() const
Definition: thread_pool.h:43
Botan::Thread_Pool::operator=
Thread_Pool & operator=(Thread_Pool &&)=delete
Botan::Thread_Pool::run
auto run(F &&f, Args &&... args) -> std::future< typename std::result_of< F(Args...)>::type >
Definition: thread_pool.h:57
Botan::Thread_Pool::operator=
Thread_Pool & operator=(const Thread_Pool &)=delete
Botan::Thread_Pool::~Thread_Pool
~Thread_Pool()
Definition: thread_pool.h:39
Botan::Thread_Pool::Thread_Pool
Thread_Pool(const Thread_Pool &)=delete
BOTAN_TEST_API
#define BOTAN_TEST_API
Definition: compiler.h:51
Botan
Definition: alg_id.cpp:13
type
MechanismType type
Definition: p11_mechanism.cpp:44