Boost :: Asio.消息在哪个线程中发送? [英] Boost::Asio. In which thread is the message sent?

查看:97
本文介绍了Boost :: Asio.消息在哪个线程中发送?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图理解boost::asio库的内部工作,这确实很棒.我编写了一个简单的客户端,可以将一条消息发送到服务器.

I'm trying to understand the internal work of boost::asio library, which is really great. I've written a simple client that sends one message to a server.

问题是-它真正在哪个线程中发送消息?

The question is - in which thread does it really send the message?

因为我使用的是async_write()方法,所以它在调用后立即返回,并且不发送任何内容.我已经评论了io_service.run()方法,此后未调用该处理程序(没关系),但是消息已发送! (我已经在服务器日志中检查了它)

Since I use async_write() method, it returns immediately after calling and doesn't send anything. I've commented the io_service.run() method, and after that the handler was not called (that's okay), but the message was sent! (I've checked it in server logs)

顺便说一句,我在编译时不使用-lpthread,而只使用-lboost_system,所以我假设整个程序在一个线程中工作,并且没有隐藏"线程.

By the way, I don't use -lpthread, just -lboost_system while compiling, so I assume the whole program works in one thread and there are no "hidden" threads.

我无法确定发送消息的位置.

I cannot make head or tail of where was the message sent.

#include <iostream>
#include <boost/asio.hpp>

const std::string str("HELLO!");

int main()
{
    boost::asio::io_service io_service;
    boost::asio::ip::tcp::endpoint endpoint(boost::asio::ip::address::from_string("127.0.0.1"), 33333);
    boost::asio::ip::tcp::socket socket(io_service);
    boost::system::error_code ec;
    boost::asio::connect(socket, &endpoint, ec);
    boost::asio::async_write(socket, boost::asio::buffer(str),
                             [](const boost::system::error_code& ec, std::size_t length)
                             {
                                 if (!ec)
                                 {
                                     std::cout << "Sent!" << std::endl;
                                 }
                                 else
                                 {
                                     std::cout << "Err: " << ec.message() << std::endl;
                                 }
    });

    //io_service.run();
    return 0;
}

推荐答案

消息将被发送(或至少在网络堆栈中排队,可能由内核线程或其他与实现相关的机制处理)您无需关心)在调用async_write的过程中.如果不必在不阻塞调用线程的情况下就可以做到这一点,那么就不必推迟了.

The message would have been sent (or at least queued in the network stack, perhaps to be handled by a kernel thread, or some other implementation-dependent mechanism that you shouldn't need to care about) during the call to async_write. There's no need to defer that, if it can be done without blocking the calling thread, which it typically can be.

在运行io_service之前,不会调用完成处理程序,并且会通知该消息已发送.

The completion handler won't be called until the io_service is run, and is notified that the message has been sent.

这篇关于Boost :: Asio.消息在哪个线程中发送?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆