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
31 if(boost::this_thread::get_id() != thread_.get_id())
\r
35 void set_capacity(size_t capacity)
\r
37 execution_queue_.set_capacity(capacity);
\r
40 void start() // noexcept
\r
42 if(is_running_.fetch_and_store(true))
\r
44 thread_ = boost::thread(f_);
\r
47 execution_queue_.clear();
\r
49 catch(boost::broken_promise&){}
\r
52 void stop() // noexcept
\r
54 is_running_ = false;
\r
55 execution_queue_.push([]{});
\r
65 std::function<void()> func;
\r
66 while(execution_queue_.try_pop(func)){}
\r
69 template<typename Func>
\r
70 auto begin_invoke(Func&& func) -> boost::unique_future<decltype(func())> // noexcept
\r
72 typedef boost::packaged_task<decltype(func())> task_type;
\r
74 auto task = task_type(std::forward<Func>(func));
\r
75 auto future = task.get_future();
\r
77 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
81 if(boost::this_thread::get_id() == thread_.get_id()) // Avoids potential deadlock.
\r
84 catch(boost::task_already_started&){}
\r
87 struct task_adaptor_t
\r
89 task_adaptor_t(const task_adaptor_t& other) : task(std::move(other.task)){}
\r
90 task_adaptor_t(task_type&& task) : task(std::move(task)){}
\r
91 void operator()() const { task(); }
\r
92 mutable task_type task;
\r
93 } task_adaptor(std::move(task));
\r
95 execution_queue_.push([=]
\r
97 try{task_adaptor();}
\r
98 catch(boost::task_already_started&){}
\r
99 catch(...){CASPAR_LOG_CURRENT_EXCEPTION();}
\r
102 return std::move(future);
\r
105 template<typename Func>
\r
106 auto invoke(Func&& func) -> decltype(func())
\r
108 if(boost::this_thread::get_id() == thread_.get_id()) // Avoids potential deadlock.
\r
111 return begin_invoke(std::forward<Func>(func)).get();
\r
114 tbb::concurrent_bounded_queue<std::function<void()>>::size_type size() const { return execution_queue_.size(); }
\r
115 bool empty() const { return execution_queue_.empty(); }
\r
116 bool is_running() const { return is_running_; }
\r
120 void execute() // noexcept
\r
122 std::function<void()> func;
\r
123 execution_queue_.pop(func);
\r
127 void run() // noexcept
\r
129 win32_exception::install_handler();
\r
134 std::function<void()> f_;
\r
135 boost::thread thread_;
\r
136 tbb::atomic<bool> is_running_;
\r
137 tbb::concurrent_bounded_queue<std::function<void()>> execution_queue_;
\r