cynric4sure
cynric4sure

Reputation: 199

boost thread and socket

I have a very weird problem. In server class, if I comment t1.join() I can not read anything from the socket in the HandleFunction. But if I uncomment t1.join(), that works just fine. But I need this listen function run forever and create a thread to handle the socket whenever it accept one. If i add join there will definately create some problem. How can i fix it? thanks in advance

class server
{
  io_service;
  acceptor;
  void listen()
  {
  for(;;)
  {
    boost::asio::ip::tcp::socket socket(io_service);
    socketPtr = &socket;
    acceptor.accept(socket);
    HandleClass objHandleClass;
    boost::thread t1(boost::bind(&HandleClass::HandleFunction, &objHandleClass, boost::ref(socketptr)));
    //t1.join();
  }
  }
}

int main()
{
  server objServer;
  objServer.listen();
}

class HandleClass
{
  HandleFunction(socket* socketPtr)
  {
    //read from this socket;
  }
}

Upvotes: 0

Views: 247

Answers (1)

Sam Miller
Sam Miller

Reputation: 24174

In your loop inside void listen()

for(;;)
  {
    boost::asio::ip::tcp::socket socket(io_service);
    socketPtr = &socket;
    acceptor.accept(socket);
    HandleClass objHandleClass;
    boost::thread t1(boost::bind(&HandleClass::HandleFunction, &objHandleClass, boost::ref(socketptr)));
    //t1.join();
  }

Your socket object will go out of scope and be destroyed every iteration of this loop, this is why you cannot read from the socket when t1.join() is commented out.

Upvotes: 1

Related Questions