线程之间传递回调函数或者任务的一种方法是使用std::packaged_task封装可调用对象,然后将std::packaged_task对象放入公共容器里面,然后被调用任务的线程持到std::packaged_task里面的future对象,当需要数据的时候调用future对象的get()或wait()方法即可阻塞并等待。执行任务的线程执行完可调用对象之后,该future就变为可获得的状态。被调用任务的线程就不再阻塞,继续执行。下面程序模拟了GUI收到更新消息并执行回调任务的例子。
//GUIThreadWorker.h
#pragma once
#include<queue>
#include<future>
#include<thread>
class GUIThreadWorker {
private:
GUIThreadWorker();
~GUIThreadWorker();
std::deque<std::packaged_task<void()> > tasks;
std::mutex lock;
bool done = false;
std::thread gui_thread;
private:
void start();
public:
GUIThreadWorker(const GUIThreadWorker& other) = delete;
GUIThreadWorker& operator=(const GUIThreadWorker& other) = delete;
static GUIThreadWorker* getInstance();
static GUIThreadWorker* instance;
static std::mutex mtx;
static std::once_flag s_flag;
template<typename Func> std::future<