我在Linux5.3(Linux5.3)上有一个C++程序,它产生多个线程,这些线程在无限循环中执行作业并休眠一定的时间。现在,我必须取消正在运行的线程,以防出现新的配置通知,并重新启动一组新的线程,为此我使用了pthread_cancel。我观察到的是,即使在接收到取消指示后,线程也不会停止,甚至一些休眠线程在休眠完成后也会出现。
由于该行为不是所希望的,因此在所提到的场景中使用pthread_cancel会引发关于实践是好是坏的问题。
请评论上面提到的场景中的pthread_cancel使用情况。
发布于 2011-01-21 23:49:45
一般来说,线程取消并不是一个好主意。只要有可能,最好使用一个共享标志,由线程使用它来中断循环。这样,您将让线程在实际退出之前执行它们可能需要执行的任何清理。
在线程没有实际取消的问题上,POSIX规范确定了一组取消点( man 7 pthreads )。只能在这些点取消线程。如果无限循环不包含取消点,则可以通过调用pthread_testcancel添加一个取消点。如果调用了pthread_cancel,则此时将对其执行操作。
发布于 2011-01-22 02:30:58
如果您正在编写异常安全的C++代码(请参阅http://www.boost.org/community/exception_safety.html),那么您的代码自然就可以进行线程取消了。glibs throws C++ exception on thread cancel,这样您的析构函数就可以进行适当的清理。
发布于 2016-12-31 05:38:46
您可以执行与以下代码等效的操作。
#include <pthread.h>
#include <cxxabi.h>
#include <unistd.h>
...
void *Control(void* pparam)
{
try
{
// do your work here, maybe long loop
}
catch (abi::__forced_unwind&)
{ // handle pthread_cancel stack unwinding exception
throw;
}
catch (exception &ex)
{
throw ex;
}
}
int main()
{
pthread_t tid;
int rtn;
rtn = pthread_create( &tid, NULL, Control, NULL );
usleep(500);
// some other work here
rtn = pthtead_cancel( tid );
}https://stackoverflow.com/questions/4760687
复制相似问题