17 #ifndef _THREAD_SYNCRONIZER_H_
18 #define _THREAD_SYNCRONIZER_H_
36 std::queue<std::function<void()>> tasks_;
37 std::atomic<bool> ready;
39 std::condition_variable condition_;
51 condition_.notify_all();
58 bool is_ready() {
return ready.load(std::memory_order_acquire); }
66 template <
class F,
class... Args>
typename std::result_of<F(Args...)>::type
enqueue_and_wait(F&& f, Args&&... args) {
78 template <
class F,
class... Args>
auto enqueue(F&& f, Args&&... args) -> std::future<
typename std::result_of<F(Args...)>::type> {
79 using return_type =
typename std::result_of<F(Args...)>::type;
80 auto task = std::make_shared<std::packaged_task<return_type()>>(std::bind(std::forward<F>(f), std::forward<Args>(args)...));
82 std::future<return_type> res = task->get_future();
84 std::unique_lock<std::mutex> lock(mutex_);
85 tasks_.emplace([task]() { (*task)(); });
87 condition_.notify_one();
97 std::unique_lock<std::mutex> lock(mutex_);
102 std::function<void()> functor = tasks_.front();
116 ready.store(
true, std::memory_order_release);
118 std::unique_lock<std::mutex> lock(mutex_);
119 while(tasks_.empty() && ready.load(std::memory_order_acquire)) {
120 condition_.wait_for(lock, std::chrono::milliseconds(10));
124 ready.store(
false, std::memory_order_release);
executes a function syncronized in another thread
auto enqueue(F &&f, Args &&... args) -> std::future< typename std::result_of< F(Args...)>::type >
std::result_of< F(Args...)>::type enqueue_and_wait(F &&f, Args &&... args)
thread_syncronizer()=default