
Hi All, can anybody explain me please why I get an access violation in the following code? And why if I enable the std::cout in the stream_handler destructor the code work fine without exception? I'm developing on windows XP, VS 2005. Regards Gianni Here is the code: #include <boost/asio.hpp> #include <boost/bind.hpp> #include <boost/thread.hpp> #include <boost/date_time/posix_time/posix_time_types.hpp> #include <iostream> typedef boost::shared_ptr<boost::asio::ip::tcp::socket> tcp_socket_ptr; class stream_handler { public: stream_handler() : acceptor(io_service) { boost::asio::ip::tcp::endpoint endpoint = boost::asio::ip::tcp::endpoint(boost::asio::ip::tcp::v4(), 22222); acceptor.open(endpoint.protocol()); acceptor.set_option(boost::asio::ip::tcp::acceptor::reuse_address(true)); acceptor.bind(endpoint); acceptor.listen(); socket = tcp_socket_ptr(new boost::asio::ip::tcp::socket(io_service)); acceptor.async_accept(*socket, boost::bind(&stream_handler::handleAcceptForDebug, this, boost::asio::placeholders::error)); work = boost::shared_ptr<boost::asio::io_service::work>(new boost::asio::io_service::work(io_service)); thread = boost::thread(boost::bind(&boost::asio::io_service::run, &io_service)); } virtual ~stream_handler() { //std::cout << __FUNCTION__ << std::endl; io_service.stop(); } private: boost::asio::io_service io_service; boost::shared_ptr<boost::asio::io_service::work> work; boost::asio::ip::tcp::acceptor acceptor; boost::thread thread; tcp_socket_ptr socket; void handleAcceptForDebug(const boost::system::error_code& iError) {}; }; int main(int argc, char** argv) { stream_handler tcpsocket; return 0; }

can anybody explain me please why I get an access violation in the following code? And why if I enable the std::cout in the stream_handler destructor the code work fine without exception?
Because you've got a race condition between stream_handler (and its private io_service) destruction, which occurs in the main thread, and the internal io_service shut-down process, which occurs in the thread that invokes io_service::run(). std::cout just take long enough to affect this race contdition. To solve the problem, add thread.join() to the destructor.
participants (2)
-
Gianni Ambrosio
-
Igor R