3 #include "../exception/exceptions.h"
\r
4 #include "../exception/win32_exception.h"
\r
6 #include <boost/thread.hpp>
\r
8 #include <tbb/atomic.h>
\r
9 #include <tbb/concurrent_queue.h>
\r
11 #include <functional>
\r
26 explicit executor(const std::function<void()>& f = nullptr)
\r
29 is_running_ = false;
\r
30 f_ = f != nullptr ? f : [this]{run();};
\r
38 void start() // noexcept
\r
40 if(is_running_.fetch_and_store(true))
\r
42 thread_ = boost::thread(f_);
\r
45 bool is_running() const // noexcept
\r
50 void stop() // noexcept
\r
52 is_running_ = false;
\r
56 void execute() // noexcept
\r
58 boost::unique_lock<boost::mutex> lock(mut_);
\r
65 bool try_execute() // noexcept
\r
67 std::function<void()> func;
\r
68 if(execution_queue_[high_priority].try_pop(func) || execution_queue_[normal_priority].try_pop(func) || execution_queue_[low_priority].try_pop(func))
\r
74 return func != nullptr;
\r
77 template<typename Func>
\r
78 auto begin_invoke(Func&& func, priority p = normal_priority) -> boost::unique_future<decltype(func())> // noexcept
\r
80 typedef decltype(func()) result_type;
\r
82 auto task = std::make_shared<boost::packaged_task<result_type>>(std::forward<Func>(func)); // boost::packaged_task cannot be moved into lambda, need to used shared_ptr.
\r
83 auto future = task->get_future();
\r
85 task->set_wait_callback(std::function<void(decltype(*task)& task)>([=](decltype(*task)& task) // The std::function wrapper is required in order to add ::result_type to functor class.
\r
89 if(boost::this_thread::get_id() == thread_.get_id()) // Avoids potential deadlock.
\r
92 catch(boost::task_already_started&){}
\r
94 execution_queue_[p].push([=]
\r
97 catch(boost::task_already_started&){}
\r
98 catch(...){CASPAR_LOG_CURRENT_EXCEPTION();}
\r
101 cond_.notify_one();
\r
103 return std::move(future);
\r
106 template<typename Func>
\r
107 auto invoke(Func&& func, priority p = normal_priority) -> decltype(func())
\r
109 if(boost::this_thread::get_id() == thread_.get_id()) // Avoids potential deadlock.
\r
112 return begin_invoke(std::forward<Func>(func), p).get();
\r
117 virtual void run() // noexcept
\r
119 win32_exception::install_handler();
\r
124 tbb::atomic<size_t> size_;
\r
125 boost::condition_variable cond_;
\r
128 std::function<void()> f_;
\r
129 boost::thread thread_;
\r
130 tbb::atomic<bool> is_running_;
\r
131 std::array<tbb::concurrent_bounded_queue<std::function<void()>>, 3> execution_queue_;
\r