libfilezilla
thread_pool.hpp
Go to the documentation of this file.
1 #ifndef LIBFILEZILLA_THREAD_POOL_HEADER
2 #define LIBFILEZILLA_THREAD_POOL_HEADER
3 
4 #include "libfilezilla.hpp"
5 #include "mutex.hpp"
6 
7 #include <functional>
8 #include <memory>
9 #include <vector>
10 
15 namespace fz {
16 
17 class thread_pool;
18 
20 class async_task_impl;
21 
24 class FZ_PUBLIC_SYMBOL async_task final {
25 public:
26  async_task() = default;
27 
30 
31  async_task(async_task const&) = delete;
32  async_task& operator=(async_task const&) = delete;
33 
34  async_task(async_task && other) noexcept;
35  async_task& operator=(async_task && other) noexcept;
36 
38  void join();
39 
41  explicit operator bool() const { return impl_ != nullptr; }
42 
44  void detach();
45 
46 private:
47  friend class thread_pool;
48 
49  async_task_impl* impl_{};
50 };
51 
53 class pooled_thread_impl;
54 
63 class FZ_PUBLIC_SYMBOL thread_pool final
64 {
65 public:
66  thread_pool();
67  ~thread_pool();
68 
69  thread_pool(thread_pool const&) = delete;
70  thread_pool& operator=(thread_pool const&) = delete;
71 
73  async_task spawn(std::function<void()> const& f);
74  async_task spawn(std::function<void()> && f);
75 
76 private:
77  FZ_PRIVATE_SYMBOL pooled_thread_impl* get_or_create_thread();
78 
79  friend class async_task;
80  friend class pooled_thread_impl;
81 
82  std::vector<pooled_thread_impl*> threads_;
83  std::vector<pooled_thread_impl*> idle_;
84  mutex m_{false};
85  bool quit_{};
86 };
87 
88 }
89 
90 #endif
Handle for asynchronous tasks.
Definition: thread_pool.hpp:24
void join()
Wait for the task to finish, adds the now idle thread back into the pool.
void detach()
Detach the running thread from the task. Once done, the thread adds itself back into the pool.
~async_task()
If task has not been detached, calls join.
Lean replacement for std::(recursive_)mutex.
Definition: mutex.hpp:52
A dumb thread-pool for asynchronous tasks.
Definition: thread_pool.hpp:64
async_task spawn(std::function< void()> const &f)
Spawns a new asynchronous task.
Sets some global macros and further includes string.hpp.
Thread synchronization primitives: mutex, scoped_lock and condition.
The namespace used by libfilezilla.
Definition: apply.hpp:17