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
53 begin_invoke([]{}); // wake if sleeping
\r
54 assert(boost::this_thread::get_id() != thread_.get_id());
\r
58 void execute() // noexcept
\r
60 boost::unique_lock<boost::mutex> lock(mut_);
\r
67 bool try_execute() // noexcept
\r
69 std::function<void()> func;
\r
70 if(execution_queue_[high_priority].try_pop(func) || execution_queue_[normal_priority].try_pop(func) || execution_queue_[low_priority].try_pop(func))
\r
76 return func != nullptr;
\r
79 template<typename Func>
\r
80 auto begin_invoke(Func&& func, priority p = normal_priority) -> boost::unique_future<decltype(func())> // noexcept
\r
82 typedef decltype(func()) result_type;
\r
84 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
85 auto future = task->get_future();
\r
87 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
91 if(boost::this_thread::get_id() == thread_.get_id()) // Avoids potential deadlock.
\r
94 catch(boost::task_already_started&){}
\r
96 execution_queue_[p].push([=]
\r
99 catch(boost::task_already_started&){}
\r
100 catch(...){CASPAR_LOG_CURRENT_EXCEPTION();}
\r
103 cond_.notify_one();
\r
105 return std::move(future);
\r
108 template<typename Func>
\r
109 auto invoke(Func&& func, priority p = normal_priority) -> decltype(func())
\r
111 if(boost::this_thread::get_id() == thread_.get_id()) // Avoids potential deadlock.
\r
114 return begin_invoke(std::forward<Func>(func), p).get();
\r
119 virtual void run() // noexcept
\r
121 win32_exception::install_handler();
\r
126 tbb::atomic<size_t> size_;
\r
127 boost::condition_variable cond_;
\r
130 std::function<void()> f_;
\r
131 boost::thread thread_;
\r
132 tbb::atomic<bool> is_running_;
\r
133 std::array<tbb::concurrent_bounded_queue<std::function<void()>>, 3> execution_queue_;
\r