造轮子系列: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 
#include 
#include 

const int EMPTY_MSG_WHAT = -1;

class Handler;
class Looper;
class BaseMessage;

typedef std::function Runnable;
using HandlerFunc = std::function)>;
using std::cout;
using std::endl;

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

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

private:
    int what_;
    std::weak_ptr 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 msg);
    std::shared_ptr getMsg();
    void popFront();
    bool empty();
    int size(){
       return msg_list_.size();
    }
private:
    std::list> msg_list_;
};

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

private:
    HandlerFunc handler_func_;
    std::shared_ptr looper_;
};

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

private:
    std::shared_ptr 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 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 msg) {
    std::unique_lock lock(msg_mutex);
    msg_list_.push_back(msg);
    msg_cv.notify_one();
}

std::shared_ptr 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) : handler_func_(func), looper_(looper) {
}

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

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

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

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

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

void Looper::loop() {
    cout << "loop start" << endl;
    for (;;) {
        std::unique_lock 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 msg) {
    this->msg_queue_->addMsg(msg);
}

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

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

#ifndef FUTURE_LOOPERTHREAD_H
#define FUTURE_LOOPERTHREAD_H
#include 
#include "msg_looper.h"
#include "promise.h"

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

    std::shared_ptr getLooper();

private:
    std::shared_ptr looper_;
    std::string name_;
};

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

#include "LooperThread.h"

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

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

std::shared_ptr 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 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是一个无参无返回的方法,也是有广泛适应性的

你可能感兴趣的:(造轮子系列:Looper、Message)