C++ Thread多线程并发记录(7)模拟主线程与子线程通信简单示例

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;
}
相关推荐
阿拉伯柠檬9 小时前
应用层协议HTTP
linux·网络·c++·网络协议·http
爱上解放晚晚9 小时前
QT转vs
c++
tryxr9 小时前
Java 中 this 关键字的使用场景
java·开发语言·类与对象·this关键字
写代码的【黑咖啡】9 小时前
面向对象编程入门:从类与对象到构造函数
开发语言·python
沐知全栈开发9 小时前
Perl POD 文档
开发语言
Dargon2889 小时前
Simulink的回调函数(二)
开发语言·matlab·simulink·mbd软件开发
ICT技术最前线9 小时前
路由策略优化基本思路和方法
开发语言·php
lly2024069 小时前
Docker 安装 Ubuntu
开发语言
摸鱼仙人~9 小时前
兼容OpenAI接口服务的实现类
开发语言·python
Y.O.U..9 小时前
GO学习-io包常用接口
开发语言·学习·golang