ASIO正确处理多线程 + strand + socket + timer
创始人
2024-11-11 10:01:05
0

下面是一个使用ASIO正确处理多线程、strand、socket和timer的代码示例:

#include 
#include 
#include 
#include 

using namespace std;

void workerThread(asio::io_context& ioContext) {
    ioContext.run();
}

void printThreadId() {
    cout << "Thread ID: " << this_thread::get_id() << endl;
}

void printMessage(const string& message) {
    printThreadId();
    cout << message << endl;
}

void handleTimer(const asio::error_code& error, asio::steady_timer* timer) {
    if (error) {
        printMessage("Timer error: " + error.message());
        return;
    }

    printMessage("Timer expired");

    timer->expires_after(chrono::seconds(1));
    timer->async_wait([timer](const asio::error_code& error) { 
        handleTimer(error, timer);
    });
}

void handleRead(const asio::error_code& error, size_t bytesTransferred) {
    if (error) {
        printMessage("Read error: " + error.message());
        return;
    }

    printMessage("Received message: " + string(buffer.data(), bytesTransferred));
}

void startRead(asio::ip::tcp::socket& socket) {
    asio::async_read(socket, asio::buffer(buffer), asio::transfer_at_least(1),
        asio::bind_executor(strand, bind(handleRead, std::placeholders::_1, std::placeholders::_2)));
}

void handleAccept(asio::ip::tcp::socket& socket, asio::io_context& ioContext) {
    printMessage("Accepted connection");

    startRead(socket);

    asio::ip::tcp::socket newSocket(ioContext);
    acceptor.async_accept(newSocket, bind(handleAccept, ref(newSocket), ref(ioContext)));
}

int main() {
    asio::io_context ioContext;
    asio::io_context::strand strand(ioContext);

    asio::ip::tcp::endpoint endpoint(asio::ip::tcp::v4(), 8888);
    asio::ip::tcp::acceptor acceptor(ioContext, endpoint);

    asio::steady_timer timer(ioContext);
    timer.expires_after(chrono::seconds(1));
    timer.async_wait([&timer](const asio::error_code& error) { 
        handleTimer(error, &timer);
    });

    vector threads;
    for (int i = 0; i < thread::hardware_concurrency(); ++i) {
        threads.emplace_back([&ioContext]() {
            workerThread(ioContext);
        });
    }

    printMessage("Server started");

    asio::ip::tcp::socket socket(ioContext);
    acceptor.async_accept(socket, bind(handleAccept, ref(socket), ref(ioContext)));

    for (auto& thread : threads) {
        thread.join();
    }

    return 0;
}

在这个示例中,首先创建了一个asio::io_context对象和一个asio::io_context::strand对象。然后,创建了一个asio::ip::tcp::acceptor对象来侦听客户端连接。接下来,创建一个asio::steady_timer对象来定期触发操作。然后,创建了多个工作线程,每个线程都运行workerThread函数,其中调用ioContext.run()来执行IO操作。

handleAccept函数中,当有新的客户端连接时,会打印一条消息,并启动一个异步读操作startRead来读取客户端发送的数据。在startRead函数中,使用asio::async_read函数来异步读取数据,并使用asio::bind_executor来绑定strand对象,以确保在同一线程中处理读取操作。

handleRead函数中,当读操作完成时,会打印接收到的消息。

handleTimer函数中,当定时器超时时,会打印一条消息,并重新启动定时器。

最后,在main函数中,创建了多个工作线程,并启动ioContext.run()来执行IO操作。然后,创建一个asio::ip::tcp::socket对象,并使用acceptor.async_accept函数异步接受客户端连接。最后,等待工作线程结束,并返回0。

相关内容

热门资讯

【NI Multisim 14...   目录 序言 一、工具栏 🍊1.“标准”工具栏 🍊 2.视图工具...
银河麒麟V10SP1高级服务器... 银河麒麟高级服务器操作系统简介: 银河麒麟高级服务器操作系统V10是针对企业级关键业务...
不能访问光猫的的管理页面 光猫是现代家庭宽带网络的重要组成部分,它可以提供高速稳定的网络连接。但是,有时候我们会遇到不能访问光...
AWSECS:访问外部网络时出... 如果您在AWS ECS中部署了应用程序,并且该应用程序需要访问外部网络,但是无法正常访问,可能是因为...
Android|无法访问或保存... 这个问题可能是由于权限设置不正确导致的。您需要在应用程序清单文件中添加以下代码来请求适当的权限:此外...
北信源内网安全管理卸载 北信源内网安全管理是一款网络安全管理软件,主要用于保护内网安全。在日常使用过程中,卸载该软件是一种常...
AWSElasticBeans... 在Dockerfile中手动配置nginx反向代理。例如,在Dockerfile中添加以下代码:FR...
AsusVivobook无法开... 首先,我们可以尝试重置BIOS(Basic Input/Output System)来解决这个问题。...
ASM贪吃蛇游戏-解决错误的问... 要解决ASM贪吃蛇游戏中的错误问题,你可以按照以下步骤进行:首先,确定错误的具体表现和问题所在。在贪...
月入8000+的steam搬砖... 大家好,我是阿阳 今天要给大家介绍的是 steam 游戏搬砖项目,目前...