title: boost::asio bug? task_io_service before destruction of io_service
body: <p>I found this weird bug inside my code. Here's the self contained test case I managed to get it down to.</p>
  
  <pre><code>#include &lt;memory&gt;
  #include &lt;thread&gt;
  #include &lt;stack&gt;
  #include &lt;system_error&gt;
  
  #include &lt;boost/asio.hpp&gt;
  
  using boost::asio::io_service;
  using std::placeholders::_1;
  
  class async_service
  {
  public:
      async_service();
      async_service(size_t number_threads);
      ~async_service();
  
      async_service(const async_service&amp;) = delete;
      void operator=(const async_service&amp;) = delete;
  
      void spawn();
      void shutdown();
  
      io_service&amp; get_service();
      const io_service&amp; get_service() const;
  
  private:
      io_service service_;
      io_service::work* work_;
      std::vector&lt;std::thread&gt; threads_;
  };
  
  async_service::async_service()
    : work_(nullptr)
  {
  }
  
  async_service::async_service(size_t number_threads)
    : work_(nullptr)
  {
      for (size_t i = 0; i &lt; number_threads; ++i)
          spawn();
  }
  
  async_service::~async_service()
  {
      std::cout &lt;&lt; __PRETTY_FUNCTION__ &lt;&lt; std::endl;
      service_.stop();
      for (std::thread&amp; t: threads_)
          t.join();
  }
  
  void run_service(io_service* service)
  {
      service-&gt;run();
  }
  
  void async_service::spawn()
  {
      if (!work_)
          work_ = new io_service::work(service_);
      threads_.push_back(std::thread(run_service, &amp;service_));
  }
  void async_service::shutdown()
  {
      delete work_;
      work_ = nullptr;
  }
  
  io_service&amp; async_service::get_service()
  {
      return service_;
  }
  const io_service&amp; async_service::get_service() const
  {
      return service_;
  }
  
  // --------------------------------------------------------------
  
  template &lt;typename... Args&gt;
  class subscriber
    : public std::enable_shared_from_this&lt;subscriber&lt;Args...&gt;&gt;
  {
  public:
      typedef std::function&lt;void (Args...)&gt; handler_type;
      typedef std::shared_ptr&lt;subscriber&lt;Args...&gt;&gt; ptr;
  
      subscriber(async_service&amp; service)
        : strand_(service.get_service())
      {
      }
  
      void subscribe(handler_type handle)
      {
          strand_.dispatch(
              std::bind(&amp;subscriber&lt;Args...&gt;::do_subscribe,
                  this-&gt;shared_from_this(), handle));
      }
  
      void relay(Args... params)
      {
          strand_.dispatch(
              std::bind(&amp;subscriber&lt;Args...&gt;::do_relay,
                  this-&gt;shared_from_this(), std::forward&lt;Args&gt;(params)...));
      }
  
  private:
      typedef std::stack&lt;handler_type&gt; registry_stack;
  
      void do_subscribe(handler_type handle)
      {
          registry_.push(handle);
      }
  
      void do_relay(Args... params)
      {
          registry_stack notify_copy = std::move(registry_);
          registry_ = registry_stack();
          while (!notify_copy.empty())
          {
              notify_copy.top()(params...);
              notify_copy.pop();
          }
          assert(notify_copy.empty());
      }
  
      io_service::strand strand_;
      registry_stack registry_;
  };
  
  // --------------------------------------------------------
  
  class lala_channel_proxy
    : public std::enable_shared_from_this&lt;lala_channel_proxy&gt;
  {
  public:
      typedef std::function&lt;void (const std::error_code&amp;)&gt; receive_inventory_handler;
  
      lala_channel_proxy(async_service&amp; service)
        : strand_(service.get_service())
      {
          inventory_subscriber_ =
              std::make_shared&lt;inventory_subscriber_type&gt;(service);
      }
  
      void start()
      {
          read_header();
      }
  
      void subscribe_inventory(receive_inventory_handler handle_receive)
      {
          inventory_subscriber_-&gt;subscribe(handle_receive);
      }
  
      typedef subscriber&lt;const std::error_code&amp;&gt; inventory_subscriber_type;
  
      void read_header()
      {
          strand_.post(
              std::bind(&amp;lala_channel_proxy::handle_read_header,
                  shared_from_this(), boost::system::error_code(), 0));
      }
  
      void handle_read_header(const boost::system::error_code&amp; ec,
          size_t bytes_transferred)
      {
          std::cout &lt;&lt; "inventory ----------" &lt;&lt; std::endl;
          inventory_subscriber_-&gt;relay(std::error_code());
          sleep(1.0);
          read_header();
      }
  
      io_service::strand strand_;
      inventory_subscriber_type::ptr inventory_subscriber_;
  };
  
  typedef std::shared_ptr&lt;lala_channel_proxy&gt; lala_channel_proxy_ptr;
  
  class lala_channel
  {
  public:
      lala_channel(async_service&amp; service)
      {
          lala_channel_proxy_ptr proxy =
              std::make_shared&lt;lala_channel_proxy&gt;(service);
          proxy-&gt;start();
          //weak_proxy_ = proxy;
          strong_proxy_ = proxy;
      }
      void subscribe_inventory(
          lala_channel_proxy::receive_inventory_handler handle_receive)
      {
          lala_channel_proxy_ptr proxy = strong_proxy_;
          proxy-&gt;subscribe_inventory(handle_receive);
      }
      lala_channel_proxy_ptr strong_proxy_;
      // Normally this has a weak pointer to the channel pimpl to allow
      // it to die, but whether it uses a weak_ptr or shared_ptr makes
      // no difference.
      //std::weak_ptr&lt;channel_proxy&gt; weak_proxy_;
  };
  
  typedef std::shared_ptr&lt;lala_channel&gt; lala_channel_ptr;
  //typedef lala_channel_proxy_ptr lala_channel_ptr;
  
  class session
    : public std::enable_shared_from_this&lt;session&gt;
  {
  public:
      typedef std::function&lt;void (const std::error_code&amp;)&gt; completion_handler;
  
      session(async_service&amp; service, async_service&amp; mempool_service,
              async_service&amp; disk_service)
        : strand_(service.get_service()),
          txpool_strand_(mempool_service.get_service()),
          chain_strand_(disk_service.get_service()), service_(service)
      {
      }
  
      void start()
      {
          auto this_ptr = shared_from_this();
          lala_channel_ptr node =
              std::make_shared&lt;lala_channel&gt;(service_);
          node-&gt;subscribe_inventory(
              std::bind(&amp;session::inventory, this_ptr, _1, node));
          for (size_t i = 0; i &lt; 500; ++i)
          {
              chain_strand_.post(
                  []()
                  {
                      std::cout &lt;&lt; "HERE!" &lt;&lt; std::endl;
                      sleep(2);
                  });
          }
      }
  
  private:
      void inventory(const std::error_code&amp; ec, lala_channel_ptr node)
      {
          if (ec)
          {
              std::cerr &lt;&lt; ec.message() &lt;&lt; std::endl;
              return;
          }
          auto this_ptr = shared_from_this();
          txpool_strand_.post([]() {});
          node-&gt;subscribe_inventory(
              std::bind(&amp;session::inventory, this_ptr, _1, node));
      }
  
      async_service&amp; service_;
      io_service::strand txpool_strand_, strand_, chain_strand_;
  };
  
  int main()
  {
      // First level
      {
          // Bug only happens for this ordering of async_service's
          // That means it is only triggered when they are destroyed in
          // this reverse order.
          async_service network_service(1), disk_service(1), mempool_service(1);
          //async_service network_service(1), mempool_service(1), disk_service(1);
          //async_service disk_service(1), mempool_service(1), network_service(1);
          //async_service disk_service(1), network_service(1), mempool_service(1);
          //async_service mempool_service(1), disk_service(1), network_service(1);
          //async_service mempool_service(1), network_service(1), disk_service(1);
  
          // Second level
          {
              // Should be kept alive by io_service
              auto s = std::make_shared&lt;session&gt;(network_service, mempool_service, disk_service);
              s-&gt;start();
          }
          //network_service.shutdown();
          //disk_service.shutdown();
          //mempool_service.shutdown();
          sleep(3);
      // Never gets past here
      }
      std::cout &lt;&lt; "Exiting..." &lt;&lt; std::endl;
      return 0;
  }
  </code></pre>
  
  <p>When I run it, I get this:</p>
  
  <pre><code>$ g++ -std=c++0x /tmp/ideone_y6OlI.cpp -lboost_system -pthread -ggdb
  $ gdb a.out 
  GNU gdb (Ubuntu/Linaro 7.4-2012.04-0ubuntu2) 7.4-2012.04
  Copyright (C) 2012 Free Software Foundation, Inc.
  License GPLv3+: GNU GPL version 3 or later &lt;http://gnu.org/licenses/gpl.html&gt;
  This is free software: you are free to change and redistribute it.
  There is NO WARRANTY, to the extent permitted by law.  Type "show copying"
  and "show warranty" for details.
  This GDB was configured as "x86_64-linux-gnu".
  For bug reporting instructions, please see:
  &lt;http://bugs.launchpad.net/gdb-linaro/&gt;...
  Reading symbols from /home/genjix/src/brokenlibbtc/a.out...done.
  (gdb) r
  Starting program: /home/genjix/src/brokenlibbtc/a.out 
  [Thread debugging using libthread_db enabled]
  Using host libthread_db library "/lib/x86_64-linux-gnu/libthread_db.so.1".
  [New Thread 0x7ffff6deb700 (LWP 28098)]
  [New Thread 0x7ffff65ea700 (LWP 28099)]
  [New Thread 0x7ffff5de9700 (LWP 28100)]
  inventory ----------
  HERE!
  inventory ----------
  HERE!
  inventory ----------
  async_service::~async_service()
  async_service::~async_service()
  [Thread 0x7ffff5de9700 (LWP 28100) exited]
  
  Program received signal SIGSEGV, Segmentation fault.
  [Switching to Thread 0x7ffff6deb700 (LWP 28098)]
  0x0000000000405873 in boost::asio::detail::task_io_service::wake_one_idle_thread_and_unlock (this=0x6255e0, lock=...) at /usr/include/boost/asio/detail/impl/task_io_service.ipp:461
  461     first_idle_thread_ = idle_thread-&gt;next;
  </code></pre>
  
  <p>Same thing with boost 1.48 and 1.49.</p>
  
  <p>I wonder why this is happening. It only happens with this highly particular configuration. If I change anything then the bug does not occur.</p>
  
  <p>async_service is a convenience wrapper around io_service. Strangely if I change the io_service to an *io_service and do not delete the io_service then the error doesn't happen... but surely it should not matter?</p>
  
  <p>If you look at the sourcecode in main(), there are 3 async_service objects created. Each one of them manages the lifetime of a single io_service.</p>
  
  <pre><code>        // Bug only happens for this ordering of async_service's
          // That means it is only triggered when they are destroyed in
          // this reverse order.
          async_service network_service(1), disk_service(1), mempool_service(1);
          //async_service network_service(1), mempool_service(1), disk_service(1);
          //async_service disk_service(1), mempool_service(1), network_service(1);
          //async_service disk_service(1), network_service(1), mempool_service(1);
          //async_service mempool_service(1), disk_service(1), network_service(1);
          //async_service mempool_service(1), network_service(1), disk_service(1);
  </code></pre>
  
  <p>The subscriber class represents a subscribe ... call thing for a particular event. The session and channel thing are adapted from a larger program so they might seem a big tangled/confusing.</p>