现代 C++ 并发服务器的核心模式

现代 C++ 并发服务器的核心模式

📁 项目结构

复制代码
concurrent-message-server/
├── CMakeLists.txt
└── src/
    └── main.cpp

📄 src/main.cpp

cpp 复制代码
// =============================================================================
// 精简并发消息服务器 - 教学版
// 特点:异步、线程安全、可扩展
// 编译: mkdir build && cd build && cmake .. && make
// 运行: ./server_demo
// =============================================================================

#include <iostream>
#include <map>
#include <functional>
#include <queue>
#include <thread>
#include <mutex>
#include <atomic>
#include <chrono>
#include <string>

using namespace std;

// ----------------------------
// 消息结构
// ----------------------------
struct Message {
    string type;
    string data;
    Message(string t = "", string d = "") : type(std::move(t)), data(std::move(d)) {}
};

using MessageHandler = function<void(const Message&)>;

// ----------------------------
// 并发消息服务器(核心)
// ----------------------------
class ConcurrentMessageServer {
private:
    // 注册表:消息类型 -> 处理函数
    map<string, MessageHandler> handlers_;

    // 消息队列(生产者-消费者缓冲区)
    queue<Message> message_queue_;
    mutable mutex queue_mutex_;

    // 控制线程生命周期
    atomic<bool> should_stop_{false};
    thread worker_thread_;

    // 后台工作线程主循环
    void worker_loop() {
        while (!should_stop_) {
            Message msg;
            {
                lock_guard<mutex> lock(queue_mutex_);
                if (message_queue_.empty()) {
                    this_thread::sleep_for(chrono::milliseconds(1));
                    continue;
                }
                msg = move(message_queue_.front());
                message_queue_.pop();
            }

            // 在无锁环境下处理消息
            auto it = handlers_.find(msg.type);
            if (it != handlers_.end()) {
                it->second(msg);
            }
        }
    }

public:
    // 注册消息处理器
    void register_handler(const string& type, MessageHandler handler) {
        handlers_[type] = move(handler);
    }

    // 异步发送消息(非阻塞)
    void send(const Message& msg) {
        lock_guard<mutex> lock(queue_mutex_);
        message_queue_.push(msg);
    }

    // 启动后台线程
    void start() {
        should_stop_ = false;
        worker_thread_ = thread(&ConcurrentMessageServer::worker_loop, this);
    }

    // 停止并等待线程结束
    void stop() {
        should_stop_ = true;
        if (worker_thread_.joinable()) {
            worker_thread_.join();
        }
    }

    ~ConcurrentMessageServer() {
        stop();
    }
};

// ----------------------------
// 演示:一个简单的 HTTP 服务器模拟
// ----------------------------
class HttpServer : public ConcurrentMessageServer {
public:
    HttpServer() {
        register_handler("GET", [](const Message& m) {
            cout << "[HTTP] GET " << m.data << "\n";
        });
        register_handler("POST", [](const Message& m) {
            cout << "[HTTP] POST " << m.data << "\n";
        });
    }
};

// ----------------------------
// 主函数
// ----------------------------
int main() {
    cout << "🚀 Starting Concurrent Message Server...\n";

    HttpServer server;
    server.start();

    // 模拟接收多个请求
    server.send(Message("GET", "/index.html"));
    server.send(Message("POST", "/api/login"));
    server.send(Message("GET", "/style.css"));

    // 给处理线程一点时间
    this_thread::sleep_for(chrono::milliseconds(100));

    server.stop();
    cout << "✅ Server stopped.\n";

    return 0;
}

📄 CMakeLists.txt

cmake 复制代码
cmake_minimum_required(VERSION 3.14)
project(ConcurrentMessageServer LANGUAGES CXX)

set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_CXX_EXTENSIONS OFF)

find_package(Threads REQUIRED)

add_executable(server_demo src/main.cpp)
target_link_libraries(server_demo PRIVATE Threads::Threads)

# 可选:启用警告
if(CMAKE_COMPILER_IS_GNUCXX OR CMAKE_CXX_COMPILER_ID MATCHES "Clang")
    target_compile_options(server_demo PRIVATE -Wall -Wextra)
endif()

✅ 项目特点(教学导向)

特性 说明
精简 核心代码仅 ~80 行,无冗余
清晰 每个组件职责分明:register_handler, send, worker_loop
并发 使用单独工作线程异步处理消息
线程安全 mutex 保护队列,atomic 控制退出
可扩展 通过继承(如 HttpServer)轻松添加新协议
现代 C++ 使用 std::function, lambda, move, lock_guard

🔧 构建与运行

bash 复制代码
git clone <your-repo> concurrent-message-server  # 或手动创建目录
cd concurrent-message-server
mkdir build && cd build
cmake ..
make
./server_demo

输出示例:

复制代码
🚀 Starting Concurrent Message Server...
[HTTP] GET /index.html
[HTTP] POST /api/login
[HTTP] GET /style.css
✅ Server stopped.

相关推荐
泡海椒4 分钟前
JQuick-Excel 实战:用 STYLE 配置单元格与区域样式
开发语言·python·excel
等我调个Bug8 分钟前
Linux基本指令
linux·服务器
Sarvartha8 小时前
final 关键字
java·开发语言
fpcc9 小时前
c++编程实践—堆和栈越界调试
c++
程序员Sunday9 小时前
JavaScript 事件循环面试题,宏任务与微任务怎么执行|Sunday面试指南
开发语言·javascript·面试·校招·事件循环·程序员sunday
_upupup9 小时前
Linux的调试工具——gdb/cgdb
linux·服务器
zhangzeyuaaa10 小时前
Ruby 多线程、GVL(GIL)与 Mutex 完全指南
开发语言·前端·ruby
weiabc10 小时前
MSYS2 UCRT64 + g++ C++ 中文输出乱码 完整全过程
c++
谢亮_vipxieliang11 小时前
用 PHP 构建轻量级 REST API:从路由到鉴权的完整实践
开发语言·后端·php
思无邪6611 小时前
用 AI 做 JS 逆向:从抓包到复现的完整方法论
开发语言·javascript·人工智能