我在我的应用程序中使用boost库进行线程和同步。跨线程的C++同步和异常处理
首先我必须说线程内的异常对于同步来说是compilitey新事物对我来说。 在下面的任何情况下,我想要实现的伪代码。我想要同步的线程抛出异常,可能从执行notify的线程中抛出异常。我怎样才能做到这一点?
无法找到有关的异常使用boost线程模型
非常感谢事先与横纱的互动扔从堆栈溢出的任何话题!
// mutex and scondition variable for the problem
mutable boost::mutex conditionMutex;
mutable boost::condition_variable condition;
inline void doTheThing() const {
if (noone doing the thing) {
try {
doIt()
// I succeeded
failed = false;
condition.notify_all();
}
catch (...) {
// I failed to do it
failed = true;
condition.notify_all();
throw
}
else {
boost::mutex::scoped_lock lock(conditionMutex);
condition.wait(lock);
if (failed) {
// throw the same exception that was thrown from
// thread doing notify_all
}
}
}
感谢您的回答。我知道我需要锁定if语句让别人通过。我刚刚从伪代码中退出了锁定。您的解决方案要求每个线程都需要通过doIt()。我想阻塞的线程等待工作线程完成它正在做的事情。实际的问题是如何将可能的异常传播给同步的线程。那么你是否说这完全不可能? – Lauri
@Lauri 1 of 2:仔细看看,只有第一个线程通过'doIt()',其余的线程在检查完成后会跳过'doIt()'。 –
@Lauri 2 of 2:我澄清了我的答案,参见上文。 –