我正在做这样的事情:
struct MyClass::Impl {
std::string someString;
//Invoked from thread "anotherThread"
void callback() {
std::cout << someString << std::endl;
}
};
void MyClass::DoSomething() {
//Connnect callback and fire operation in another thread
anotherThread.Start();
anotherThread.Op1();
//Wait to finish without joining, Op1 invokes callback from another thread
//...
//string written in main thread
impl->someString = someOtherString;
anotherThread.Op2();
//Wait to finish without joining, Op2 invokes callback from anotherThread
}
问题是我无法在回调中看到 impl->someString
变化,即使它已被写入。我需要任何额外的同步吗?回调仅读取,但从不写入该字符串。
最佳答案
当在一个线程中写入一个值并在另一个线程中访问该值时,您需要进行适当的同步。如果两个线程中没有适当的同步,就会出现数据竞争。任何数据竞争都会导致您的程序出现未定义的行为。
关于c++ - 在另一个线程 visual studio 2012 中看不到 std::string 的变化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24119668/