An executor that launches a new thread for each function submitted to it. This class satisfies the executor requirements.
| 25 | // An executor that launches a new thread for each function submitted to it. |
| 26 | // This class satisfies the executor requirements. |
| 27 | class thread_executor |
| 28 | { |
| 29 | private: |
| 30 | // Service to track all threads started through a thread_executor. |
| 31 | class thread_bag : public execution_context::service |
| 32 | { |
| 33 | public: |
| 34 | typedef thread_bag key_type; |
| 35 | |
| 36 | explicit thread_bag(execution_context& ctx) |
| 37 | : execution_context::service(ctx) |
| 38 | { |
| 39 | } |
| 40 | |
| 41 | void add_thread(std::thread&& t) |
| 42 | { |
| 43 | std::unique_lock<std::mutex> lock(mutex_); |
| 44 | threads_.push_back(std::move(t)); |
| 45 | } |
| 46 | |
| 47 | private: |
| 48 | virtual void shutdown() |
| 49 | { |
| 50 | for (auto& t : threads_) |
| 51 | t.join(); |
| 52 | } |
| 53 | |
| 54 | std::mutex mutex_; |
| 55 | std::vector<std::thread> threads_; |
| 56 | }; |
| 57 | |
| 58 | public: |
| 59 | execution_context& query(execution::context_t) const |
| 60 | { |
| 61 | return boost::asio::query(system_executor(), execution::context); |
| 62 | } |
| 63 | |
| 64 | execution::blocking_t query(execution::blocking_t) const |
| 65 | { |
| 66 | return execution::blocking.never; |
| 67 | } |
| 68 | |
| 69 | thread_executor require(execution::blocking_t::never_t) const |
| 70 | { |
| 71 | return *this; |
| 72 | } |
| 73 | |
| 74 | template <class Func> |
| 75 | void execute(Func f) const |
| 76 | { |
| 77 | thread_bag& bag = use_service<thread_bag>(query(execution::context)); |
| 78 | bag.add_thread(std::thread(std::move(f))); |
| 79 | } |
| 80 | |
| 81 | friend bool operator==(const thread_executor&, |
| 82 | const thread_executor&) noexcept |
| 83 | { |
| 84 | return true; |