简体   繁体   中英

Boost.Asio SSL mystic threads

I noticed that the following code starts 2 threads (Windows 8.1, MSVC 2013). After ~10 seconds of waiting at acceptor.accept() , it will spawn 2 additional threads. If the process is idle for a few minutes, it will be reduced to three.

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

using namespace boost::asio;

int main(int argc, char** argv)
{
    int test;

    ssl::context ctx(ssl::context::tlsv12_server);

    /* ctx settings */

    io_service io_service;

    ssl::stream<ip::tcp::socket> socket(io_service, ctx);
    ip::tcp::acceptor acceptor(io_service, ip::tcp::endpoint(ip::tcp::v4(), 4433), false);

    acceptor.accept(socket.lowest_layer());

    socket.handshake(ssl::stream_base::server);

    read(socket, buffer(&test, sizeof(test)));

    boost::system::error_code error;
    socket.shutdown(error);
    if (error && error != boost::asio::error::eof) throw boost::system::system_error(error);

    socket.lowest_layer().shutdown(ip::tcp::socket::shutdown_both);
    socket.lowest_layer().close();
}

This behavior is a bit strange for me, I don't even use a single async operation, thread or something.


I did some tests, it seems the problem only occurs when I use SSL sockets. These two examples (blocking and non-blocking as well) start only one thread.

I also tried this "official" asynchronous SSL example, but it produces the same problem.


What causes this problem? Can I eliminate this behavior?

Have you debugged the threads (inspect the call stacks to see what's running).

Anyways, Asio IO services may implement their operations using emulated asynchrony if true asynchrony is not available. True (OS level) asynchrony should be available for regular files, sockets, COM (serial) ports etc.

I can imagine that the Boost Asio SSL implementation uses such a background thread to emulate some stateful things related to the SSL protocol. You could look into the documentation to see whether this is the case.¹

However, all things being equal you already have

  • some evidence this is the case (the extra threads don't appear unless you're using SSL)
  • the means to find out (just stop the program when the "mystic threads" appear and inspect the call stacks for them

¹ On a related note, threads are used to manage timers in eg ./detail/impl/win_iocp_io_service.ipp

Update As the OP has found, this lead was exactly spot-on:

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM