为什么和什么时候不应该杀死线程? [英] Why and when shouldn't I kill a thread?

查看:196
本文介绍了为什么和什么时候不应该杀死线程?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个多线程套接字服务器,我需要确定。

I am writing a multithreaded socket server and I need to know for sure.

线程文章说我应该等待线程返回,而不是杀死它。在某些情况下,虽然,用户的线程我想踢/禁止,将无法正常返回(例如,我开始发送一个大块的数据和send()块的线程在这一刻)所以我会

Articles about threads say that I should wait for the thread to return, instead of killing it. In some cases though, the user's thread i want to kick/ban, will not be able to return properly (for example, I started to send a big block of data and send() blocks the thread at the moment) so I'll need just to kill it.

为什么要杀死线程函数是危险的,什么时候它们会崩溃整个应用程序?

Why killing thread functions are dangerous and when can they crash the whole application?

推荐答案

杀死一个线程意味着停止所有的执行正好在那一刻。特别是,它不会执行任何析构函数。这意味着套接字和文件不会被关闭,动态分配的内存不会被释放,互斥体和信号量将不会被释放等。杀死一个线程几乎可以保证导致资源泄漏和死锁。

Killing a thread means stopping all execution exactly where it is a the moment. In particular, it will not execute any destructors. This means sockets and files won't be closed, dynamically-allocated memory will not be freed, mutexes and semaphores won't be released, etc. Killing a thread is almost guaranteed to cause resource leaks and deadlocks.

因此,你的问题是反转的。真正的问题应该是:

Thus, your question is kind of reversed. The real question should read:


在什么时候,在什么条件下 >

When, and under what conditions can I kill a thread?

所以,你可以杀死线程,当你确信没有泄漏和死锁可能发生,而不是现在,而不是当其他线程的代码

So, you can kill the thread when you're convinced no leaks and deadlocks can occur, not now, and not when the other thread's code will be modified (thus, it is pretty much impossible to guarantee).

在您的特定情况下,解决方案是使用非阻塞套接字,并在调用 send() recv()之间检查一些线程/用户特定标志。这可能会使您的代码复杂化,这可能是为什么您一直拒绝这样做,但这是正确的方式。

In your specific case, the solution is to use non-blocking sockets and check some thread/user-specific flag between calls to send()and recv(). This will likely complicate your code, which is probably why you've been resisting to do so, but it's the proper way to go about it.

此外,意识到每个客户端线程的方法不会扩展,所以你将改变你的架构,并重写大量的它。无论如何。

Moreover, you will quickly realize that a thread-per-client approach doesn't scale, so you'll change your architecture and re-write lots of it anyways.

这篇关于为什么和什么时候不应该杀死线程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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