How to Destroy a thread object [duplicate]

柔情痞子 提交于 2019-12-11 17:36:42

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/46827203/how-to-destroy-a-thread-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!