Reputation: 7663
I am doing something like this:
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
}
The problem is that I cannot see impl->someString
change in callback, even if it has been written to. Do I need any additional synchronization? Callback only reads, but never writes that string.
Upvotes: 0
Views: 75
Reputation: 153840
When writing a value in one thread and accessing the value in another thread you need to have appropriate synchronization. Without proper synchronization in both threads you have a data race. Any data race causes your program to have undefined behavior.
Upvotes: 3