lintel 0.2.0
Loading...
Searching...
No Matches
ExecutorService.h
Go to the documentation of this file.
1#ifndef LOGGING_EXECUTORSERVICE_H
2#define LOGGING_EXECUTORSERVICE_H
3
4#include <atomic>
5#include <functional>
6#include <future>
7#include <mutex>
8#include <queue>
9#include <thread>
10#include <type_traits>
11
12namespace lintel {
17{
18private:
19 std::atomic<bool> m_exit = false;
20 std::mutex m_mutex;
21 std::condition_variable m_conditionVariable;
22 typedef std::function<void()> TASK;
23 std::queue<TASK> m_tasks;
24 std::thread m_runnable;
25
27 void run();
28
29public:
31 ExecutorService() : m_runnable([&]() { run(); }) {}
32
35 {
36 {
37 // m_exit must be flipped under the mutex the worker's predicate reads under,
38 // otherwise the notify_all() can slip into the window between the predicate
39 // check and the wait, and the join() below hangs forever.
40 std::lock_guard<std::mutex> lock(m_mutex);
41 m_exit = true;
42 }
43 m_conditionVariable.notify_all();
44 m_runnable.join();
45 }
46
55 template<class F, class... Args>
56 std::future<typename std::invoke_result<typename std::decay<F>::type, typename std::decay<Args>::type...>::type>
57 execute(F &&f, Args &&...args);
58};
59
60template<class F, class... Args>
61std::future<typename std::invoke_result<typename std::decay<F>::type, typename std::decay<Args>::type...>::type>
63{
64 auto func = std::make_shared<std::packaged_task<
65 typename std::invoke_result<typename std::decay<F>::type, typename std::decay<Args>::type...>::type()>>(
66 std::bind(std::forward<F>(f), std::forward<Args>(args)...));
67 auto future = func->get_future();
68 {
69 std::unique_lock<std::mutex> lock(m_mutex);
70 m_tasks.push([=, func = std::move(func)]() { (*func)(); });
71 }
72 m_conditionVariable.notify_one();
73 return future;
74}
75
76}// namespace lintel
77#endif// LOGGING_EXECUTORSERVICE_H
Definition ExecutorService.h:17
std::future< typename std::invoke_result< typename std::decay< F >::type, typename std::decay< Args >::type... >::type > execute(F &&f, Args &&...args)
Definition ExecutorService.h:62
ExecutorService()
Definition ExecutorService.h:31
~ExecutorService()
Definition ExecutorService.h:34
Definition BaseFeature.h:6
constexpr std::string_view type_name()
Definition TypeName.h:9