C ++ kill方法没有不断检查标志 [英] C++ kill method without constantly checking flags
问题描述
我有几个工作功能,调用附件功能,可能有一些不好的发生。我想要能够停止工作功能,如果附件功能确定发生了坏事,没有在工作功能中进行大量的标志检查。例如,
I have several work functions, that call accessory functions that might have something bad happen. I want to be able to stop the work functions if an accessory function determines something bad happened, without putting numerous flag checks in the work functions. For example,
struct Worker {
bool badhappened = false;
Worker() {
std::thread([&]() {
while ( not badhappened );
// kill the work
}).detach();
}
int WorkComponent {
if ( badhappening() )
badhappened = true;
return someint;
}
void DoWork {
// WorkComponents called several times
}
}
但是我不知道在下调用什么工作
。这不是一个问题, DoWork
发生在一个单独的线程,但似乎没有一个等价的 pthread_kill
在C ++的线程。是否有一个解决方案不涉及将多个 if(badhappened)return; 调用到
DoWork
?
But I don't know what to call at kill the work
. It's not a problem for DoWork
to happen in a separate thread, but there doesn't appear to be an equivalent pthread_kill
in C++'s threads. Is there a solution that doesn't involve putting several if(badhappened) return;
calls into DoWork
?
推荐答案
长故事:
停止非协作线程。
是的,有工具强制关闭线程,但是你要求麻烦。唯一安全的方法是商定终止政策。
Yes, there are tools to forcibly shut down a thread but you are asking for trouble. The only safe way is to agree on a termination policy. This boils down to checking a flag sufficiently frequently as you write.
更多关于此的信息:
C ++及以上2011:Scott ,Andrei和Herb - 向我们询问任何问题
查看30:44什么是系统原则的线程终止和程序终止?
See at 30:44 What's the deal with systematic and principled thread termination and program termination?
在POSIX中取消会话不是一个好主意:
Canceling a thread is not a good idea in POSIX either:
a href =http://stackoverflow.com/q/4760687/341970>使用pthread_cancel取消一个线程:好的做法或坏的
Cancelling a thread using pthread_cancel : good practice or bad
这篇关于C ++ kill方法没有不断检查标志的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!