Skip to content

Instantly share code, notes, and snippets.

@maddanio
Created May 28, 2018 10:25
Show Gist options
  • Save maddanio/1acf2c673c23280536d2795ba153b457 to your computer and use it in GitHub Desktop.
Save maddanio/1acf2c673c23280536d2795ba153b457 to your computer and use it in GitHub Desktop.
#pragma once
#include <functional>
#include <vector>
#include <mutex>
#include <thread>
#include <condition_variable>
#include <stlab/concurrency/task.hpp>
#include <boost/circular_buffer.hpp>
struct single_thread_executor_t
{
private:
typedef stlab::task<void()> work_item_t;
boost::circular_buffer<work_item_t> _work;
std::mutex _mutex;
std::condition_variable _condition;
std::thread _worker;
bool _quit{false};
public:
single_thread_executor_t()
: _worker{work_item_t{
[&]() -> void
{
for(;;)
{
std::unique_lock<std::mutex> lock{_mutex};
_condition.wait(lock, [&]{
return _quit || !_work.empty();
});
if (_quit)
break;
auto f = std::move(_work.back());
_work.pop_back();
lock.unlock();
f();
}
}
}}
{
}
using result_type = void;
template <typename F>
void operator()(F f)
{
using f_t = decltype(f);
std::unique_lock<std::mutex> lock{_mutex};
if (_work.full())
_work.set_capacity(_work.capacity() + 1);
_work.push_front(std::move(f));
_condition.notify_one();
}
~single_thread_executor_t()
{
std::unique_lock<std::mutex> lock{_mutex};
_quit = true;
_condition.notify_one();
lock.unlock();
_worker.join();
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment