/** * This file demonstrates how handlers wrapped with one strand are * executed on a different strand and how this can lead to deadlocks. */ #include #include #include #include #include namespace { class Test { public: Test(boost::asio::io_service& io_service) : m_io_service(io_service) , m_strand(io_service) { } void block() { while (true) { std::cout << this << ": strand.impl_" << strand().impl_ << ": " << __FUNCTION__ << ": Hello world!" << "\n"; sleep(1); } } void print() { std::cout << this << ": strand.impl_" << strand().impl_ << ": " << __FUNCTION__ << ": Hello world!" << "\n"; boost::shared_ptr pPrinter(new Test(m_io_service)); m_io_service.post(pPrinter->strand().wrap(boost::bind(&Test::print, pPrinter))); } boost::asio::strand& strand() { return (m_strand); } boost::asio::io_service& m_io_service; boost::asio::strand m_strand; }; } int main() { boost::asio::io_service io_service; /** * The handler will block which will stall the strand. Any further * handlers wrap with this strand will never run. */ Test blocker(io_service); io_service.post(blocker.strand().wrap(boost::bind(&Test::block, blocker))); /** * The handler will print "Hello World" and then create a new instantiation * of the class and and post a similarly wrapped handler. "Hello World" * should be printed forever. However eventually the printer's strand will * share the implemention of the strand belonging to "blocker" and will not * be executed. */ boost::shared_ptr pPrinter(new Test(io_service)); io_service.post(pPrinter->strand().wrap(boost::bind(&Test::print, pPrinter))); pPrinter.reset(); boost::thread thread(boost::bind(&boost::asio::io_service::run, boost::ref(io_service))); io_service.run(); thread.join(); }