我是多线程新手。我在 unix 上使用 c++。
在下面的代码中,runSearch() 需要很长时间,我希望能够在“cancel == true”时立即终止搜索。函数 cancelSearch 被另一个线程调用。
解决这个问题的最佳方法是什么?
谢谢你..
----------------这是现有的代码------------------------ -
struct SearchTask : public Runnable
{
bool cancel = false;
void cancelSearch()
{
cancel = true;
}
void run()
{
cancel = false;
runSearch();
if (cancel == true)
{
return;
}
//...more steps.
}
}
编辑:为了更清楚,假设 runSearch() 需要 10 分钟才能运行。 1 分钟后,cancel==true,然后我想立即退出 run(),而不是再等 9 分钟让 runSearch() 完成。
最佳答案
您需要在整个搜索操作中不断检查标志。像这样:
void run()
{
cancel = false;
while (!cancel)
{
runSearch();
//do your thread stuff...
}
}
关于c++ - 使用线程取消搜索,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11746770/