前言:
一直使用android的Handler,非常方便好用,但是当我使用C++编程时,想使用Android Handler一样的编程模式,竟不知如何下手,网上找了很久,都没找到具体的实现,也可能是我找的不够多。这两天沉下心来自己写了一个,省的自己去找了,以后肯定还能用到,最好有网友也做了类似实现,我可以借鉴下以提升自己。
代码参考Android Handler,有兴趣的朋友可以去看看Android 里面的实现。Android Handler 使用epoll 实现,我这里做了个简化版本,使用条件变量实现。
handler.h
#pragma once
#include "message.h"
#include <chrono>
#include <condition_variable>
#include <functional>
#include <list>
#include <map>
#include <mutex>
#include <thread>
using namespace std;
/*
* Handler will run in it's own thread, you don't want to care about it.
* Message will be proccess by the Handler. Two ways to add your task to the Handler.
* 1. send message to the handler
* 2. post the task(Function) to handler
*/
namespace es {
class Handler {
public:
using TimePoint_t = std::chrono::steady_clock::time_point;
using Clock_t = std::chrono::steady_clock;