问题描述
我在Linux(CentOS 5.3)上有一个C ++程序,产生了多个线程,这些线程处于无限循环中,执行一个作业并在某些分钟内休眠。
现在我必须取消正在运行的线程,以防万一新的配置通知进来和新开始新的线程集,我已经使用pthread_cancel。
我观察到的是,线程并没有停止,即使在收到取消指示后,即使一些睡眠线程在睡眠完成后出现。
I have a C++ program on Linux (CentOS 5.3) spawning multiple threads which are in an infinite loop to perform a job and sleep for certain minutes.Now I have to cancel the running threads in case a new configuration notification comes in and freshly start new set of threads, for which i have used pthread_cancel.What I observed was, the threads were not getting stopped even after receiving cancel indication,even some sleeping threads were coming up after the sleep was completed.
该行为不是所期望的,在所提及的场景中使用pthread_cancel引发了关于好或坏做法的问题。
As the behavior was not desired, usage of pthread_cancel in the mentioned scenario raises question about being good or bad practice.
请在上述情况下对pthread_cancel使用进行评论。
Please comment on the pthread_cancel usage in above mentioned scenario.
推荐答案
一般来说线程取消不是一个好主意。更好的是,只要有可能,有一个共享标志,由线程使用的突破循环。这样,你将允许线程执行任何清理,他们可能需要做之前实际退出。
In general thread cancellation is not a really good idea. It is better, whenever possible, to have a shared flag, that is used by the threads to break out of the loop. That way, you will let the threads perform any cleanup they might need to do before actually exiting.
在线程实际上不取消的问题,POSIX规范确定一组取消点()。线程只能在这些点取消。如果你的无限循环不包含取消点,你可以通过调用 pthread_testcancel
添加一个。如果 pthread_cancel
已被调用,那么它将在此时执行。
On the issue of the threads not actually cancelling, the POSIX specification determines a set of cancellation points ( man 7 pthreads ). Threads can be cancelled only at those points. If your infinite loop does not contain a cancellation point you can add one by calling pthread_testcancel
. If pthread_cancel
has been called, then it will be acted upon at this point.
这篇关于使用pthread_cancel取消一个线程:好的做法还是坏的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!