Exception 无法在多线程解决方案中捕获抛出的对象
我有一个解决内线程问题的RAII类:Exception 无法在多线程解决方案中捕获抛出的对象,exception,c++11,constructor,raii,stdthread,Exception,C++11,Constructor,Raii,Stdthread,我有一个解决内线程问题的RAII类: #include <iostream> #include <thread> using namespace std; struct solution_using_thread { solution_using_thread() : alive_(true), thread_() { thread_ = thread([this]() { while(alive_);
#include <iostream>
#include <thread>
using namespace std;
struct solution_using_thread {
solution_using_thread()
: alive_(true), thread_() {
thread_ = thread([this]() {
while(alive_);
});
}
~solution_using_thread() {
alive_ = false;
thread_.join();
}
private:
bool alive_;
thread thread_;
};
int main() {
cout << 0 << endl;
try {
solution_using_thread solution;
throw 1;
} catch (int i ) {
cout << i << endl;
}
cout << 2 << endl;
}
本来应该是:
0
1
2
在中,它始终仅为0
我错过了什么
抱歉,标题不明确。请不要犹豫,为这个问题建议一个更好的方法。您假设线程(最终)将看到
活动的更新值。但这并不能保证。没有同步的对象不能保证在任何有限的时间内对其他线程可见。alive\uu
的值可能缓存在某个地方,并且从未更新过
您需要一些同步来使其工作,或者使用互斥锁或其他同步原语,或者使活动
原子。下面是后者的一个例子:
#include <atomic>
struct solution_using_thread {
solution_using_thread()
: alive_(true), thread_() {
thread_ = thread([this]() {
while(alive_);
});
}
~solution_using_thread() {
alive_ = false;
thread_.join();
}
private:
atomic<bool> alive_;
thread thread_;
};
#包括
使用线程的结构解决方案{
使用线程()的解决方案
:活动线程(true),线程{
线程=线程([此](){
活着的时候;
});
}
~solution_使用_线程(){
活着=假;
螺纹连接();
}
私人:
原子活度;
螺纹螺纹;
};
在没有任何同步的情况下,程序具有未定义的行为,因为在接受您的回答之前,两个线程通过活动
进入数据竞争,您能否解释一下为什么堆栈展开不会在线程
(在原始代码中)阻塞?@bmm补充说,没有同步,它是UB,所以任何事情都可能发生(包括不阻塞)。
#include <atomic>
struct solution_using_thread {
solution_using_thread()
: alive_(true), thread_() {
thread_ = thread([this]() {
while(alive_);
});
}
~solution_using_thread() {
alive_ = false;
thread_.join();
}
private:
atomic<bool> alive_;
thread thread_;
};