c++ - 在另一个线程 visual studio 2012 中看不到 std::string 的变化

标签 c++ multithreading visual-studio-2012

我正在做这样的事情:

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/

相关文章:

c++ - 在子类中实现纯虚方法

c++ - 好友类 : Cannot Access private members?

c# - 如何将参数从控制台应用程序 c# 传递到正在运行的进程?使用wcf?

java - 如果父线程较早完成,则子线程似乎无法完成

c++ - 不存在的行上的C++编译错误

c++ - 运行时检查失败 #2 - 变量 's' 周围的堆栈已损坏

c++ - macos 开发qt app 使用rapidjson 如何获取正确的中文?

python - 如何从 boost 线程调用 Python?

c++ - 非 MFC ATL 项目 (dll) 产生 MFC 相关错误

c++ - C++ Switch 语句中的十六进制值