ASIO正确处理多线程 + strand + socket + timer
创始人
2024-11-11 10:01:44
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。

相关内容

热门资讯

安卓换鸿蒙系统会卡吗,体验流畅... 最近手机圈可是热闹非凡呢!不少安卓用户都在议论纷纷,说鸿蒙系统要来啦!那么,安卓手机换上鸿蒙系统后,...
iwatch怎么连接安卓系统,... 你有没有想过,那款时尚又实用的iWatch,竟然只能和iPhone好上好?别急,今天就来给你揭秘,怎...
iphone系统与安卓系统更新... 最近是不是你也遇到了这样的烦恼?手机更新系统总是失败,急得你团团转。别急,今天就来给你揭秘为什么iP...
安卓系统拦截短信在哪,安卓系统... 你是不是也遇到了这种情况:手机里突然冒出了很多垃圾短信,烦不胜烦?别急,今天就来教你怎么在安卓系统里...
安卓系统怎么连不上carlif... 安卓系统无法连接CarLife的原因及解决方法随着智能手机的普及,CarLife这一车载互联功能为驾...
app安卓系统登录不了,解锁登... 最近是不是你也遇到了这样的烦恼:手机里那个心爱的APP,突然就登录不上了?别急,让我来帮你一步步排查...
windows官网系统多少钱 Windows官网系统价格一览:了解正版Windows的购买成本Windows 11官方价格解析微软...
oppo手机安卓系统换成苹果系... OPPO手机安卓系统换成苹果系统:现实吗?如何操作?随着智能手机市场的不断发展,用户对于手机系统的需...
安卓系统如何卸载app,轻松掌... 手机里的App越来越多,是不是感觉内存不够用了?别急,今天就来教你怎么轻松卸载安卓系统里的App,让...
安卓平板改windows 系统... 你有没有想过,你的安卓平板电脑是不是也能变身成Windows系统的超级英雄呢?想象在同一个设备上,你...