Elegantly stop the thread to block or non-block when accepting or receiving using asio and C ++ 11

I am using asio for tcp server and I plan to use C ++ 11 std for stream. My ultimate goal is an application for Linux, but I will test it on Windows first with Visual Studio 2015.

I use blocking at first, so I found that there was a discussion of how to stop a thread waiting to be accepted. There were pre-C ++ 11 solutions like pipe and select. I am looking for a way asio.

asio::io_service io_service; tcp::acceptor acceptor(io_service, tcp::endpoint(tcp::v4(), 13)); backAcceptor = &acceptor; tcp::socket socket(io_service); asio::error_code ec; acceptor.accept(socket, &ec); 

The second way is to use asynchronous, but I prefer to use only the asio header. The compilation complained that asio :: placeholder does not have this member, but according to the comment, the solution is applied:

  asio::async_write(socket_, asio::buffer(message_), std::bind(&tcp_connection::handle_write, shared_from_this(), std::placeholders::_1, std::placeholders::_2 )); 

run () is still blocking. And I'm looking for a method to resume this thread from the main one.

  asio::io_service io_service; tcp_server server(io_service); io_service.run(); 

The third way is to set the timeout here . But this does not prevent me from agreeing. Plus, the answer was in 2012. Hope this already needs a new solution.

Update

To test the scripts, I first have a thread for both blocks during synchronous accept () or when running asynchronously (). When the thread is running, the master then waits 2 seconds and tries to stop the thread. Then I wait for the thread to complete using the connection.

For the first "Synchronous" method, I tried using acceptor.cancel () and the stream received during the connection. Is it correct?

The second method is "Async", although it is still unclear how to officially end this topic, I managed to use io_service.stop () to actually cancel it.

Please let me know if my decisions are correct and I will continue to use various solutions.

+1
source share
1 answer

I happen to play with a non-standard approach with run_one and without streaming, which specifically allows you to time out individual "non-asynchronous" operations:

In fact, you send asynchronous operations, but then you call await_operation with a timeout:

 async_connect(socket, ip::tcp::resolver(ioservice).resolve({address, port}), raise()); await_socket(std::chrono::seconds(6)); 

This is equivalent to doing a synchronous connect , but with a timeout option. Not a single thread, run() lock or other puppies were harmed.

See related answer for demos.


PS. Use deadline_timer with posix_time if you don't want high_resolution_timer work with std::chrono

+1
source

Source: https://habr.com/ru/post/888385/


All Articles