title: Thread pool using boost asio
body: <p>I am trying to create a limited thread pool class using boost::asio. But I am stuck at one point can some one help me.</p>
  
  <p>The only problem is the place where I should decrease counter?</p>
  
  <p>code does not work as expected.</p>
  
  <p>the problem is I don't know when my thread will finish execution and how I will come to know that it has return to pool </p>
  
  <pre><code>#include &lt;boost/asio.hpp&gt;
  #include &lt;iostream&gt;
  #include &lt;boost/thread/thread.hpp&gt;
  #include &lt;boost/bind.hpp&gt;
  #include &lt;boost/thread/mutex.hpp&gt;
  #include &lt;stack&gt;
  
  using namespace std;
  using namespace boost;
  
  class ThreadPool
  {
      static int count;
      int NoOfThread;
      thread_group grp;
      mutex mutex_;
      asio::io_service io_service;
      int counter;
      stack&lt;thread*&gt; thStk ;
  
  public:
      ThreadPool(int num)
      {   
          NoOfThread = num;
          counter = 0;
          mutex::scoped_lock lock(mutex_);
  
          if(count == 0)
              count++;
          else
              return;
  
          for(int i=0 ; i&lt;num ; ++i)
          {
              thStk.push(grp.create_thread(boost::bind(&amp;asio::io_service::run, &amp;io_service)));
          }
      }
      ~ThreadPool()
      {
          io_service.stop();
          grp.join_all();
      }
  
      thread* getThread()
      {
          if(counter &gt; NoOfThread)
          {
              cout&lt;&lt;"run out of threads \n";
              return NULL;
          }
  
          counter++;
          thread* ptr = thStk.top();
          thStk.pop();
          return ptr;
      }
  };
  int ThreadPool::count = 0;
  
  
  struct callable
  {
      void operator()()
      {
          cout&lt;&lt;"some task for thread \n";
      }
  };
  
  int main( int argc, char * argv[] )
  {
  
      callable x;
      ThreadPool pool(10);
      thread* p = pool.getThread();
      cout&lt;&lt;p-&gt;get_id();
  
      //how i can assign some function to thread pointer ?
      //how i can return thread pointer after work done so i can add 
  //it back to stack?
  
  
      return 0;
  }
  </code></pre>