[英]Boost Asio, async UDP client - crash on shutdown
我在應用程序中將UDP客戶端服務器用於IPC
它工作正常,但是當嘗試關閉客戶端時,會發生一些競爭情況,這會導致應用程序崩潰或死鎖。
UDP客戶端:
// IOServiceBase class contain boost::asio::io_service instance
// it is accessible by service() protected method
class AsyncUDPClient : public IOServiceBase
{
public:
/// @brief Create a network client
AsyncUDPClient(const std::string& host, const std::string port)
: _host(host)
, _port(port)
, _reply()
, _work(service())
, _sock(service(), ba_ip::udp::endpoint(ba_ip::udp::v4(), 0)) {
run();
}
/// @brief Start async packets processing
void run(){
std::thread t([&]{ service().run(); });
t.detach();
}
/// @brief Async request to server
void send(uint8_t* message, size_t length) {
std::vector<uint8_t> packet(message, message + length);
service().post(boost::bind(&AsyncUDPClient::do_send, this, packet));
}
/// @brief Cleanup io_service to dismiss already putted tasks
~AsyncUDPClient() {
close();
// trying to wait until service is stopped, but it does not help
while (!service().stopped()){
std::this_thread::sleep_for(std::chrono::milliseconds(100));
}
}
/// @brief Cleanup io_service to dismiss already putted tasks
void close(){
std::thread t([&]{ service().stop(); });
t.join();
}
protected:
// send-response methods are pretty standard
private:
std::string _host;
std::string _port;
std::array<uint8_t, max_length> _reply;
ba::io_service::work _work;
ba_ip::udp::socket _sock;
};
用法示例:
{
AsyncUDPClient ipc(addr, port);
ipc.send(&archive_data[0], archive_data.size());
// it seems client is destroyed before some internal processing is finished?
}
行為不是確定性的,有時工作正常,有時崩潰,有時凍結。 Stacktrace在boost.asio內部的某個地方顯示崩潰點
銷毀AsyncUDPClient
無法與運行io_service
的線程正確同步。 當處理io_service
的線程在其生命周期結束后嘗試與AsyncUDPClient
及其io_service
進行交互時,這可能導致調用未定義的行為。
要解決此問題,請不要與處理io_service
的線程分離,並在io_service
停止后顯式加入線程。
class AsyncUDPClient
: public IOServiceBase
{
public:
// ...
void run()
{
_threads.emplace_back([&]{ service().run(); })
}
// ...
~AsyncUDPClient()
{
close();
}
void close()
{
// Stop the io_service. This changes its state and return immediately.
service().stop();
// Explicitly synchronize with threads running the io_service.
for (auto& thread: _threads)
{
thread.join();
}
}
private:
// ...
std::vector<std::thread> _threads;
};
如以上注釋所暗示, io_service::stop()
不會阻止。 它將io_service
的狀態更改為已停止,立即返回,並使run()
和run_one()
所有調用盡快返回。 調用io_service::stopped()
立即返回io_service
的狀態。 這些調用均未指示在run()
或run_one()
的調用中是否存在線程。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.