1.创建线程启动停止基类
2.创建主线程消息发送处理类
3.实现建议的消息处理逻辑
cpp
#ifndef CREATETH_XTHREAD_H
#define CREATETH_XTHREAD_H
#include <thread>
class XThread{
public:
//启动线程
void start();
//停止线程,设置标记位
void stop();
//检查线程是否退出
bool is_exit();
private:
std::thread th_;
bool exit_flag_ = false;
//线程入口函数
virtual void Main() = 0;
//等待线程退出
void wait();
};
#endif //CREATETH_XTHREAD_H
cpp
#include "xthread.h"
//启动线程
void XThread::start(){
exit_flag_ = false;
th_ = std::thread(&XThread::Main, this);
}
//停止线程,设置标记位
void XThread::stop(){
if (!exit_flag_)
exit_flag_ = true;
wait();
}
//等待线程退出
void XThread::wait(){
if (th_.joinable())
th_.join();
}
//检查线程是否退出
bool XThread::is_exit(){
return exit_flag_;
}
cpp
#ifndef CREATETH_XMESSAGE_H
#define CREATETH_XMESSAGE_H
#include "xthread.h"
#include <string>
#include <mutex>
#include <deque>
class XMessage : public XThread{
public:
void send(const std::string &msg);
private:
std::mutex buffer_mutex_;
std::deque<std::string> send_buffer_;
void Main() override;
};
#endif //CREATETH_XMESSAGE_H
cpp
#include "xmessage.h"
#include <iostream>
void XMessage::send(const std::string &msg) {
std::unique_lock<std::mutex> lock(buffer_mutex_);
send_buffer_.push_back(std::move(msg));
}
void XMessage::Main() {
while (!is_exit()) {
std::unique_lock<std::mutex> lock(buffer_mutex_);
std::this_thread::sleep_for(std::chrono::microseconds(100));
if (!send_buffer_.empty()) {
std::string tmp = send_buffer_.front();
send_buffer_.pop_front();
std::cout << tmp << std::endl;
} else{
continue;
}
}
}
cpp
#include "xmessage.h"
#include <sstream>
using namespace std;
int main() {
XMessage xMsg;
xMsg.start();
for (int i = 0; i < 10; ++i) {
stringstream ss;
ss << "MSG : " << i + 1;
xMsg.send(ss.str());
std::this_thread::sleep_for(std::chrono::microseconds(1000));
}
xMsg.stop();
return 0;
}