如何销毁线程对象 [英] How to Destroy a thread object

查看:388
本文介绍了如何销毁线程对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写基于C ++的多线程聊天服务器。

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.

我想在客户端断开连接时销毁线程,因此我正确设置了此功能,以便在客户端发送退出消息时调用Terminate()。

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.

但是Terminate()不仅销毁了单个线程,还销毁了所有线程。

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?

推荐答案

您不必执行任何特殊操作。

You don't have to do anything special.

std :: thread 在其构造函数中获得一个可调用对象作为参数,而该可调用对象是线程运行的函数。

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


  • 在客户端断开连接时从客户端处理功能中退出

  • 分离线程

一个简单的设计可能类似于:

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.

这篇关于如何销毁线程对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆