Question

When constructing a new std::thread, is there a point to wrapping the callable in std::bind?

I'm pretty unfamiliar with modern C++, but I've been looking at the Boost.Beast sample files and trying to understand how they work.

Specifically, I've been looking at this http server sample.

Here's a simplified version of what I'm trying to understand:

void do_session(
    tcp::socket& socket,
    ssl::context& ctx,
    std::shared_ptr<std::string const> const& doc_root
);


int main(int argc, char* argv[])
{
    if (argc != 4)
    {
        std::cerr <<
            "Usage: http-server-sync-ssl <address> <port> <doc_root>\n" <<
            "Example:\n" <<
            "    http-server-sync-ssl 0.0.0.0 8080 .\n";
        return EXIT_FAILURE;
    }
    auto const address = net::ip::make_address(argv[1]);
    auto const port = static_cast<unsigned short>(std::atoi(argv[2]));
    auto const doc_root = std::make_shared<std::string>(argv[3]);

    net::io_context ioc{1};
    ssl::context ctx{ssl::context::tlsv12};
    load_server_certificate(ctx);
    tcp::acceptor acceptor{ioc, {address, port}};

    for(;;)
    {
        // This will receive the new connection
        tcp::socket socket{ioc};

        // Block until we get a connection
        acceptor.accept(socket);

        // Launch the session, transferring ownership of the socket
        std::thread{std::bind(
            &do_session,
            std::move(socket),
            std::ref(ctx),
            doc_root)}.detach();
    }
}

At the bottom, when the thread is being created, &do_session is wrapped in std::bind before being passed to the std::thread constructor. As far as I understand, the parameters could be passed into the thread constructor. Is there a functional or performance difference in just writing std::thread(&do_session, std::move(socket), std::ref(ctx), doc_root)?

I was under the impression that these two would be functionally the same, but I'm assuming that the author of this file knows something that I don't...

 3  79  3
1 Jan 1970

Solution

 0

When constructing a new std::thread, is there a point to wrapping the callable in std::bind?

With modern c++, no there is no need to pass the callable to std::bind and then pass that to std::thread.

Basically, the callable can be passed directly to std::thread.

2024-07-18
user12002570