2019-11-08 02:56:32 +08:00
|
|
|
#pragma once
|
|
|
|
|
|
|
|
#include <future>
|
|
|
|
#include <thread>
|
|
|
|
#include <functional>
|
|
|
|
#include <queue>
|
|
|
|
#include <atomic>
|
|
|
|
|
|
|
|
// OnThreadExecutor allows its caller to off-load some work to a persistently running background thread.
|
|
|
|
// This might come in handy if you use the API which sets thread-wide global state and the state needs
|
|
|
|
// to be isolated.
|
|
|
|
|
2020-03-05 18:07:06 +08:00
|
|
|
class OnThreadExecutor final
|
|
|
|
{
|
2019-11-08 02:56:32 +08:00
|
|
|
public:
|
2020-03-05 18:07:06 +08:00
|
|
|
using task_t = std::packaged_task<void()>;
|
2019-11-08 02:56:32 +08:00
|
|
|
|
2020-03-05 18:07:06 +08:00
|
|
|
OnThreadExecutor();
|
|
|
|
~OnThreadExecutor();
|
|
|
|
std::future<void> submit(task_t task);
|
2019-11-08 02:56:32 +08:00
|
|
|
|
|
|
|
private:
|
2020-03-05 18:07:06 +08:00
|
|
|
void worker_thread();
|
2019-11-08 02:56:32 +08:00
|
|
|
|
2020-03-05 18:07:06 +08:00
|
|
|
std::mutex _task_mutex;
|
|
|
|
std::condition_variable _task_cv;
|
|
|
|
std::atomic_bool _shutdown_request;
|
|
|
|
std::queue<std::packaged_task<void()>> _task_queue;
|
2020-08-11 16:39:18 +08:00
|
|
|
std::thread _worker_thread;
|
2019-11-08 02:56:32 +08:00
|
|
|
};
|