造轮子系列:Looper、Message

android中的消息队列非常经典,Looper内部循环,从消息队列中取消息,然后再交由对应的handler执行,handler负责发送消息。

今天由c++来实现下这套系统,当然可能会略有不同,比如android中使用了epoll机制

Linux pipe/epoll机制,简单说就是在主线程的MessageQueue没有消息时,便阻塞在loop的queue.next()中的nativePollOnce()方法里,此时主线程会释放CPU资源进入休眠状态,直到下个消息到达或者有事务发生,通过往pipe管道写端写入数据来唤醒主线程工作。这里采用的epoll机制,是一种IO多路复用机制,可以同时监控多个描述符,当某个描述符就绪(读或写就绪),则立刻通知相应程序进行读或写操作,本质同步I/O,即读写是阻塞的。 所以说,主线程大多数时候都是处于休眠状态,并不会消耗大量CPU资源。

为了简单处理,本例中就使用wait和notify这种简单方式,消费者生产者模型,当消息队列中没有消息时,则阻塞线程,当往消息队列中添加消息时,则唤醒线程。

一:整体设计

首先,整个系统中会有以下几个必备的类

  • Message,消息本身,可以分成两类,runnable或根据what值处理的空消息
  • MessageQueue,消息队列,负责添加消息,给Looper提供消息
  • Handler,负责处理只有what值的空白消息
  • Looper,开启循环,从消息队列中取消息,然后处理消息
  • Thread,线程封装类,启动线程,并且在线程回调中启动Looper的循环

二:编码

#ifndef FUTURE_MSG_LOOPER_H
#define FUTURE_MSG_LOOPER_H
#include <list>
#include <iostream>
#include <functional>

const int EMPTY_MSG_WHAT = -1;

class Handler;
class Looper;
class BaseMessage;

typedef std::function<void()> Runnable;
using HandlerFunc = std::function<bool(std::shared_ptr<BaseMessage>)>;
using std::cout;
using std::endl;

class BaseMessage : public std::enable_shared_from_this<BaseMessage>{
public:
    virtual void run() = 0;
    virtual int what() = 0;
};

class Message : public BaseMessage{
public:
    explicit Message(int what, std::weak_ptr<Handler> ptr);
    void run() override;
    int what() override;

private:
    int what_;
    std::weak_ptr<Handler> weak_handler_;
};

class RunnableMsg : public BaseMessage {
public:
    explicit RunnableMsg(Runnable runnable);
    void run() override;
    int what() override;

private:
    Runnable runnable_;
};

class MessageQueue{
public:
    void addMsg(std::shared_ptr<BaseMessage> msg);
    std::shared_ptr<BaseMessage> getMsg();
    void popFront();
    bool empty();
    int size(){
       return msg_list_.size();
    }
private:
    std::list<std::shared_ptr<BaseMessage>> msg_list_;
};

class Handler : public std::enable_shared_from_this<Handler>{
public:
    explicit Handler(HandlerFunc func, std::shared_ptr<Looper> looper);
    void handleMsg(std::shared_ptr<BaseMessage> msg);
    std::shared_ptr<BaseMessage> obtainMsg(int what);
    static std::shared_ptr<Handler> createHandler(HandlerFunc func, std::shared_ptr<Looper> looper);

private:
    HandlerFunc handler_func_;
    std::shared_ptr<Looper> looper_;
};

class Looper : public std::enable_shared_from_this<Looper>{
public:
    Looper();
    void loop();
    void postMsg(std::shared_ptr<BaseMessage> msg);
    void postRunnable(Runnable runnable);
    void shutDown();

private:
    std::shared_ptr<MessageQueue> msg_queue_;
    bool shutdown_;
};


#endif //FUTURE_MSG_LOOPER_H

//-------------------------------------------------
#include "msg_looper.h"

std::mutex msg_mutex;
std::condition_variable msg_cv;

Message::Message(int what, std::weak_ptr<Handler> ptr)
    : what_(what), weak_handler_(ptr) {
}

void Message::run() {
    auto ptr = weak_handler_.lock();
    if (ptr != nullptr) {
        ptr->handleMsg(shared_from_this());
    }
}

int Message::what() {
    return what_;
}

RunnableMsg::RunnableMsg(Runnable runnable): runnable_(runnable) {
}

void RunnableMsg::run() {
    if (runnable_ != nullptr) {
        runnable_();
    }
}

int RunnableMsg::what() {
    return EMPTY_MSG_WHAT;
}

void MessageQueue::addMsg(std::shared_ptr<BaseMessage> msg) {
    std::unique_lock<std::mutex> lock(msg_mutex);
    msg_list_.push_back(msg);
    msg_cv.notify_one();
}

std::shared_ptr<BaseMessage> MessageQueue::getMsg() {
    if (msg_list_.empty()) {
        return nullptr;
    } else {
        auto msg = msg_list_.front();
        return msg;
    }
}

void MessageQueue::popFront() {
    if (msg_list_.size() > 0) {
        msg_list_.pop_front();
    }
}

bool MessageQueue::empty() {
    return msg_list_.empty();
}

Handler::Handler(HandlerFunc func, std::shared_ptr<Looper> looper) : handler_func_(func), looper_(looper) {
}

std::shared_ptr<Handler> Handler::createHandler(HandlerFunc func, std::shared_ptr<Looper> looper) {
    std::shared_ptr<Handler> handler = std::make_shared<Handler>(func, looper);
    return handler;
}

std::shared_ptr<BaseMessage> Handler::obtainMsg(int what) {
    auto msg = std::make_shared<Message>(what, shared_from_this());
    return msg;
}

void Handler::handleMsg(std::shared_ptr<BaseMessage> msg) {
    handler_func_(msg);
}

Looper::Looper() : shutdown_(false) {
    msg_queue_ = std::make_shared<MessageQueue>();
    postRunnable([](){
       cout << "the first run msg" << endl;
    });
}

void Looper::shutDown() {
    shutdown_ = true;
}

void Looper::loop() {
    cout << "loop start" << endl;
    for (;;) {
        std::unique_lock<std::mutex> lock(msg_mutex);
        cout << "msg queue.size = " << msg_queue_->size() << endl;
        msg_cv.wait(lock, [this](){
            return !(this->msg_queue_->empty()) || shutdown_;
        });
        if (shutdown_) {
            cout << "looper shut down" << endl;
            break;
        }
        auto msg = msg_queue_->getMsg();
        cout << "what = " << msg->what() << endl;
        msg->run();
        msg_queue_->popFront();
    }
}

void Looper::postMsg(std::shared_ptr<BaseMessage> msg) {
    this->msg_queue_->addMsg(msg);
}

void Looper::postRunnable(Runnable runnable) {
    std::shared_ptr<RunnableMsg> msg = std::make_shared<RunnableMsg>(runnable);
    this->msg_queue_->addMsg(msg);
}

//--------------------------------------

#ifndef FUTURE_LOOPERTHREAD_H
#define FUTURE_LOOPERTHREAD_H
#include <thread>
#include "msg_looper.h"
#include "promise.h"

class LooperThread{
public:
    LooperThread(std::string name);
    void createThread();

    std::shared_ptr<Looper> getLooper();

private:
    std::shared_ptr<Looper> looper_;
    std::string name_;
};

//----------------------------------------------

#include "LooperThread.h"

LooperThread::LooperThread(std::string name): name_(name){
    this->looper_ = std::make_shared<Looper>();
}

void LooperThread::createThread() {
    std::thread thread([this](){
        this->looper_->loop();
    });
    thread.detach();
}

std::shared_ptr<Looper> LooperThread::getLooper() {
    if (looper_ == nullptr){
        std::cout << "thread looper is null" << endl;
    } else {
        std::cout << "thread looper is not null" << endl;
    }
    return looper_;
}


#endif //FUTURE_LOOPERTHREAD_H

//-----------------------------------------------
void test_looper_thread(){
    LooperThread looperThread("ok");
    looperThread.createThread();

    std::string str = "test ok";

    cout << "-----" << endl;

    auto looper = looperThread.getLooper();
    looper->postRunnable([&str](){
        test_printf_in_looper(str);
    });

    auto handler = Handler::createHandler([](std::shared_ptr<BaseMessage> msg)->bool{
            if (msg->what() != EMPTY_MSG_WHAT) {
                cout << "msg what = " << msg->what() << endl;
            }
            return true;
        }, looper);
    auto message = handler->obtainMsg(10);
    looper->postMsg(message);

    getchar();
}

三、总结

c++的线程回调方法比较奇怪,是不能直接用类的成员方法的,因为类的成员方法中会被默认添加一个隐藏参数,this,而且是第一个参数。

***  Func(this, ...)

类的成员方法就类似上面的Func方法,它的第一个参数是this,所以如果用它作为线程的回调函数,会出现参数不匹配的情况,无法编译通过。

但c++有无赖的lambda,lambda可以捕捉当前可见的局部变量,包括this,所以可以在lambda中调用相应的成员方法。

仔细思考下例中的Runnable,它其实是一个无参但也无返回的方法,但我们往线程中调用的方法不可能一直无参也无返回值的,参数可以通过lambda的捕捉添加进来,返回值当然是通过future带出去。所以即使Runnable是一个无参无返回的方法,也是有广泛适应性的

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 194,088评论 5 459
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,715评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,361评论 0 319
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,099评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 60,987评论 4 355
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,063评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,486评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,175评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,440评论 1 290
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,518评论 2 309
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,305评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,190评论 3 312
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,550评论 3 298
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,880评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,152评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,451评论 2 341
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,637评论 2 335

推荐阅读更多精彩内容