我有一个程序产生多个线程,每个线程执行一个长期运行的任务.然后主线程等待所有工作线程加入,收集结果并退出.
如果其中一个工作程序发生错误,我希望其余的工作程序正常停止,以便主线程可以在不久之后退出.
我的问题是如何最好地执行此操作,当长期运行的任务的实现由我的代码无法修改的库提供时.
这是系统的简单草图,没有错误处理:
void threadFunc()
{
// Do long-running stuff
}
void mainFunc()
{
std::vector<std::thread> threads;
for (int i = 0; i < 3; ++i) {
threads.push_back(std::thread(&threadFunc));
}
for (auto &t : threads) {
t.join();
}
}
Run Code Online (Sandbox Code Playgroud)
如果长时间运行的函数执行循环并且我可以访问代码,那么只需通过检查每次迭代顶部的共享"keep on running"标志就可以中止执行.
std::mutex mutex;
bool error;
void threadFunc()
{
try {
for (...) {
{
std::unique_lock<std::mutex> lock(mutex);
if (error) {
break;
}
}
}
} catch (std::exception &) {
std::unique_lock<std::mutex> lock(mutex);
error = true;
}
}
Run Code Online (Sandbox Code Playgroud)
现在考虑一下库提供长时间运行的情况:
std::mutex mutex;
bool error; …
Run Code Online (Sandbox Code Playgroud)