3 #include "../exception/win32_exception.h"
\r
4 #include "../log/log.h"
\r
6 #include <tbb/atomic.h>
\r
7 #include <tbb/concurrent_queue.h>
\r
9 #include <boost/thread.hpp>
\r
10 #include <boost/noncopyable.hpp>
\r
12 #include <functional>
\r
17 class executor : boost::noncopyable
\r
21 explicit executor(const std::function<void()>& f = nullptr)
\r
23 is_running_ = false;
\r
24 f_ = f != nullptr ? f : [this]{run();};
\r
32 void start() // noexcept
\r
34 if(is_running_.fetch_and_store(true))
\r
36 thread_ = boost::thread(f_);
\r
39 void stop(bool wait = true) // noexcept
\r
41 is_running_ = false;
\r
42 execution_queue_.push([]{});
\r
43 if(wait && boost::this_thread::get_id() != thread_.get_id())
\r
47 template<typename Func>
\r
48 auto begin_invoke(Func&& func) -> boost::unique_future<decltype(func())> // noexcept
\r
50 typedef boost::packaged_task<decltype(func())> task_type;
\r
52 auto task = task_type(std::forward<Func>(func));
\r
53 auto future = task.get_future();
\r
55 task.set_wait_callback(std::function<void(task_type&)>([=](task_type& my_task) // The std::function wrapper is required in order to add ::result_type to functor class.
\r
59 if(boost::this_thread::get_id() == thread_.get_id()) // Avoids potential deadlock.
\r
62 catch(boost::task_already_started&){}
\r
65 struct task_adaptor_t
\r
67 task_adaptor_t(const task_adaptor_t& other) : task(std::move(other.task)){}
\r
68 task_adaptor_t(task_type&& task) : task(std::move(task)){}
\r
69 void operator()() const { task(); }
\r
70 mutable task_type task;
\r
71 } task_adaptor(std::move(task));
\r
73 execution_queue_.try_push([=]
\r
75 try{task_adaptor();}
\r
76 catch(boost::task_already_started&){}
\r
77 catch(...){CASPAR_LOG_CURRENT_EXCEPTION();}
\r
80 return std::move(future);
\r
83 template<typename Func>
\r
84 auto invoke(Func&& func) -> decltype(func())
\r
86 if(boost::this_thread::get_id() == thread_.get_id()) // Avoids potential deadlock.
\r
89 return begin_invoke(std::forward<Func>(func)).get();
\r
92 tbb::concurrent_bounded_queue<std::function<void()>>::size_type size() const { return execution_queue_.size(); }
\r
93 bool empty() const { return execution_queue_.empty(); }
\r
94 bool is_running() const { return is_running_; }
\r
98 void execute() // noexcept
\r
100 std::function<void()> func;
\r
101 execution_queue_.pop(func);
\r
105 void run() // noexcept
\r
107 win32_exception::install_handler();
\r
112 std::function<void()> f_;
\r
113 boost::thread thread_;
\r
114 tbb::atomic<bool> is_running_;
\r
115 tbb::concurrent_bounded_queue<std::function<void()>> execution_queue_;
\r