boost :: asio挂起_endthreadx

时间:2018-08-29 17:04:28

标签: c++ c++11 boost boost-asio

int main(){
  boost::asio::io_context io_context;
  Server server(io_context, SOCKET_ADDRESS, SOCKET_PORT);

  std::thread thread_server([&]() {
    server.start();
    io_context.run();
  });

  std::thread thread_client([&]() {
    Client &client = Client::create(SOCKET_ADDRESS, SOCKET_PORT);
    client.start();
    done = true; // <-----atomic
  });

  std::thread thread_stop([&]() {
    while (done == false) {
      std::this_thread::sleep_for(std::chrono::milliseconds(5));
    }
    server.stop();
  });

  thread_server.join();
  thread_client.join();
  thread_stop.join();
}

我正在尝试boost::asio,遇到了无法解决的问题。当我在Linux(与gcc编译)上运行程序(上面的简单示例)时,一切都很好。我在VS2017CE的Release上运行时也是如此。但是,当我在Debug(VS2017CE)上运行它时,它也会崩溃并出现异常:

  

无法取消引用字符串迭代器,因为字符串迭代器无效

退出_endthreadxthread_stop(很可能是第二个)时,它在thread_server上崩溃。然后是我的问题:

  1. Release和Debug基本配置之间的区别是什么,这些区别可能会影响代码执行并向我指出我应该去哪里看(我知道一些,但找不到与此特定问题有关的任何东西。)

  2. 我犯了什么错误,影响了代码执行。

我已经制作了一些类,因此如有必要,我将提供更多代码,但是代码基本上可以工作,因此我仅从其中一部分开始。

1 个答案:

答案 0 :(得分:2)

显示的代码对字符串没有任何作用。另外,您不会显示io_context实例中正在使用的Client

正如所给的,一切都是巨大的竞争条件,因为可能没有任何客户端工作可以运行,但是您总是在发布(应该是)异步操作后立即设置done = true Client::start中的。

(这里可能的理智解释是,如果Client::start()实际上是完全同步的,那真的会使static Client& Client::create(...)的全部存在变得很奇怪并且毫无用处吗?)

使用线程休眠是一种反模式,在异步代码中则是如此。


  

无法取消引用字符串迭代器,因为字符串迭代器无效

这清楚表明MSVC的Iterator Debugging正在运行。它只是告诉您您有编程错误。

您的错误导致字符串迭代器不再有效时被使用。我看不到它,但是99%的时间是由使用异步操作完成之前被破坏(或修改)的缓冲区的异步操作引起的。简而言之:

void foo() {
    std::string msg = "message";
    boost::asio::async_write(_socket, boost::asio::buffer(msg), /*...*/);
}

建议代码

简化代码,并显示一些提示:

Live On Coliru

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

using boost::asio::ip::tcp;
using boost::system::error_code;

static std::string const SOCKET_ADDRESS = "127.0.0.1";
static unsigned short const SOCKET_PORT = 6767;

bool check(error_code const& ec, char const* message) {
    std::cout << message << " (" << ec.message() << ")\n";
    return !ec;
}

struct Server {
    boost::asio::io_context& io_;
    Server(boost::asio::io_context& io, std::string host, unsigned short port) : io_(io), host_(host), port_(port) {}

    void start() {
        acc_.set_option(tcp::acceptor::reuse_address(true));
        acc_.listen(5);

        accept_loop();
    }

    void stop() {
        io_.post([this] { // thread safety
            acc_.cancel();
            acc_.close();
        });
    }

  private:
    void accept_loop() {
        acc_.async_accept(sock_, [this](error_code ec) {
            if (check(ec, "accepted")) {
                std::make_shared<Connection>(std::move(sock_))->start();
                accept_loop();
            }
        });
    }

    struct Connection : std::enable_shared_from_this<Connection> {
        tcp::socket sock_;
        std::string buffer_;

        Connection(tcp::socket&& sock) : sock_(std::move(sock)) {}

        ~Connection() {
            error_code ec;
            std::cout << "Disconnected " << sock_.remote_endpoint(ec) << "\n";
        }

        void start() {
            auto self = shared_from_this();

            async_read_until(sock_, boost::asio::dynamic_buffer(buffer_), "\n", [self,this](error_code ec, size_t bytes) {
                 if (check(ec, "received request")) {
                     std::cout << "Request: " << std::quoted(buffer_.substr(0, bytes), '\'') << "\n";
                     if (bytes > 0)
                         std::reverse(buffer_.begin(), buffer_.begin() + bytes - 1); // reverse the request for the response

                     async_write(sock_, boost::asio::buffer(buffer_, bytes), [self,this](error_code ec, size_t bytes) {
                          if (check(ec, "response sent")) {
                              buffer_.erase(0, bytes);
                              start(); // handle more requests, if any
                          }
                     });
                 }
            });
        }
    };

    std::string host_;
    unsigned short port_;

    tcp::acceptor acc_{io_, {boost::asio::ip::address_v4::from_string(host_), port_}};
    tcp::socket sock_{io_};
};

struct Client {
    Client(std::string host, std::string port) : host_(host), port_(port) {}

    void start() { 
        boost::asio::io_context io;

        tcp::socket s(io);
        tcp::resolver r(io);
        connect(s, r.resolve(host_, port_));

        send_request(s, "hello world\n");
        send_request(s, "bye world\n");
    }

  private:
    void send_request(tcp::socket& s, std::string const& request) {
        write(s, boost::asio::buffer(request));

        boost::asio::streambuf sb;
        read_until(s, sb, "\n");

        std::cout << "Received server response: '" << &sb << "'\n";
    }

    std::string host_;
    std::string port_;
};

int main(){
    boost::asio::io_context io_context;
    Server server(io_context, SOCKET_ADDRESS, SOCKET_PORT);
    server.start();

    std::thread thread_server([&]() { io_context.run(); });

    {
        Client client {SOCKET_ADDRESS, std::to_string(SOCKET_PORT)};
        client.start();
    }

    {
        Client client {SOCKET_ADDRESS, std::to_string(SOCKET_PORT)};
        client.start();
    }

    server.stop();
    thread_server.join();
}

打印

accepted (Success)
received request (Success)
Request: 'hello world
'
response sent (Success)
Received server response: 'dlrow olleh
'
received request (Success)
Request: 'bye world
'
response sent (Success)
Received server response: 'dlrow eyb
'
received request (End of file)
Disconnected 127.0.0.1:49778
accepted (Success)
received request (Success)
Request: 'hello world
'
response sent (Success)
Received server response: 'dlrow olleh
'
received request (Success)
Request: 'bye world
'
response sent (Success)
Received server response: 'dlrow eyb
'
received request (End of file)
Disconnected 127.0.0.1:49780
accepted (Operation canceled)
  

注意。这是一场创业比赛。根据您的运气,第一个Client可能会在Server开始监听之前尝试连接。我假设这不是您最担心的问题,我将其留给读者练习。