我有一个函数,它必须搜索网络中的所有pc并寻找响应:
DLL void get_remote_ip(void)
{
initWSA();
if(create_Sockets() == INVALID_SOCKET)
{
std::cerr << "Socket Errorn";
return;
};
initiate_TXRX_variables();
boost::asio::io_service io_service;
udp_server_search server(io_service);
std::cout << "No crash till heren";
boost::thread thread_1 = boost::thread(ultra_spam_network_udp);
boost::asio::deadline_timer dt1 = boost::asio::deadline_timer(io_service);
boost::thread thread_2(boost::bind(&boost::asio::io_service::run, &io_service));
dt1.expires_from_now(boost::posix_time::milliseconds(2000));
dt1.wait();
//ip_adr_ccd = server.return_ip(0);
if(ip_adr_ccd != "localhost" && ip_adr_daisy != "localhost")
{
std::cout << "Remote IP of CCD is: " << ip_adr_ccd << 'n';//For debug
std::cout << "Remote IP of TERS is: " << ip_adr_daisy << 'n'; //For debug
}
else
std::cout << "No new remote ips foundn";
//std::cout << Use << 'n';
//thread_1.join();
}
当我调用这个函数时,我的程序有时会崩溃而不告诉我原因,它只是告诉我"<十六进制地址>中的异常错误"。我的虫子在哪里?是否有可能一个线程尝试连接,但另一个线程现在还没有完成(这是可能的,因为错误是随机的,并且在写过程中杀死主线程的std::cout-output)?
谢谢你!十六进制地址>
我发现我的错误,我必须先停止io_service
,然后调用thread_2.join()
,否则我的thread_2崩溃
你似乎没有以一种干净的方式阻止io_service
。io_serice::run
块,而有剩余的处理程序要调度。我的猜测是,您的udp_server_search
导致处理程序的无休止排队。因此,要么你的连接永远不会结束,因为它必须等待run()
返回,而这永远不会发生,或者如果你注释掉它,留下get_remote_ip
将破坏io_service
,而在thread_2
中,run
方法继续在现在已被破坏的对象上执行。
可以解决您的问题(除了打破服务器上的无尽队列)是手动停止ioservice:
boost::thread thread_2( [&]{io_service.run();} );
//do stuff, wait for the timer etc...
io_service.stop(); //run should return as soon as possible
thread_2.join(); //clean finishing of the service.