0

I am writing a C++ based multithreaded chat server.

When a new client joins, the main thread creates a new thread to manage the client.

I want to destroy the thread when the client disconnects, so I properly setup this functionality, such that when the client sends an exit message Terminate() is called.

But Terminate(), instead of destroying just the single thread, it destroyed all the threads.

What should be done so that only the thread which i want to destroy is destroyed?

Daniel Trugman
  • 8,186
  • 20
  • 41
Vedant
  • 145
  • 1
  • 13
  • 1
    Hmm. Usually, a thread ends when it returns from its main function. – Scheff's Cat Oct 19 '17 at 11:16
  • are you sure this is the design you want? it's a recipe for scalability problems later – David Haim Oct 19 '17 at 14:07
  • @David Hamim I am making this project for grade 12 computer science project. So scalability and efficiency is not something of my concern as what i am making itself is very advanced for my level( syllabus is c++basics , classes , data handling and linked list stacks and queues. – Vedant Oct 19 '17 at 14:12

1 Answers1

2

You don't have to do anything special.

std::thread gets a callable as a parameter in its constructor and that callable is the function the thread runs.

If that callable ends at some point, a detached thread can clean itself up. just make sure to

  • exit from the client-handling-function when the client disconnect
  • detach the thread

A simplistic design can be similar to this:

while(server.is_on()){
   auto client = server.acccept_client();
   std::thread thread([client = std::move(client)]{
     handle_client_until_disconnection(client);
   });
   thread.detach();
}

another approach is to use a thread-pool. that thread-pool is constructed when the application goes up, and destroyed when application exits.

David Haim
  • 25,446
  • 3
  • 44
  • 78