Message.h 可根据实际情况定义
#pragma once
#include <algorithm>
#include <iostream>
#include <memory>
#include <string>
#include <vector>
#include <functional>
class Dispatcher;
using std::string;
class Message: public std::enable_shared_from_this<Message> {
friend class Dispatcher;
private:
int m_h;
string get_message_name();
public:
virtual ~Message() = 0;
string to_string();
Message(const Message &) = delete;
Message &operator=(const Message &) = delete;
Message() = delete;
virtual bool isSameMessage(std::shared_ptr<Message> msg);
void set_next_hop(Dispatcher* dispatcher) {
m_next_hop = dispatcher;
}
Dispatcher* get_next_hop() {
return m_next_hop;
}
protected:
string mName;
Dispatcher* m_next_hop;
};
inline string Message::get_message_name() { return mName; }
inline string Message::to_string() { return get_message_name(); }
looper是一个thread+一个Messagequeue
MyLooper.h
#pragma once
#ifndef _MY_LOOPER_H__
#define _MY_LOOPER_H__
#include <thread>
#include <shared_mutex>
#include "Message.h"
#include "MessageQueue.h"
class Dispatcher;
class MyLooper {
protected:
string mName;
Dispatcher *mDispatcher;
std::unique_ptr<MessageQueue> mMessageQueue;
std::thread* mLooperThread;
public:
static constexpr bool FEATURE_DYNAMIC_THREAD = false;
std::shared_timed_mutex looperMutex;
std::condition_variable_any looperCv;
bool isLooperReady;
bool mExit;
bool mReleaseThread;
MyLooper();
virtual ~MyLooper();
void init(Dispatcher *dispatcher);
void dispatch(std::shared_ptr<Message> msg);
void dispatchSync(std::shared_ptr<Message> msg);
void handleMessage(std::shared_ptr<Message> msg);
void handleMessageSync(std::shared_ptr<Message> msg);
size_t getSize();
bool isEmptyQueue();
void dumpMessageQueue();
std::shared_ptr<Message> getFirstMessage();
std::thread *getLooperThread();
void acquireThread();
void releaseThread();
string to_string();
void waitForLooperToConsumeAllMsgs();
void killLooper();
};
inline MyLooper::MyLooper(){
mExit = false;
mLooperThread = nullptr;
mMessageQueue = std::unique_ptr<MessageQueue>(new MessageQueue);
};
inline MyLooper::~MyLooper() {
if (mMessageQueue) {
mMessageQueue->clear();
}
killLooper();
if (mLooperThread != nullptr) {
mLooperThread->join();
delete mLooperThread;
mLooperThread = nullptr;
}
mMessageQueue = nullptr;
};
inline std::thread *MyLooper::getLooperThread() { return mLooperThread; }
inline string MyLooper::to_string() { return mName; }
#endif
MyLooper.cpp
#inclu

本文介绍了一个基于C++实现的消息队列和调度器的设计方案,包括Message、MessageQueue和Dispatcher等关键类的定义与功能实现,适用于多线程环境下的任务调度与消息传递。

1073

被折叠的 条评论
为什么被折叠?



