Let's say there is a simple class Counter
which contains a integer member count
. A new object of Counter
is constructed and count
is initialized to some number.
Now, if I pass a pointer to this object to a new thread as an argument, would the new thread always and instantly see the value that was initialized in the main thread? If so, how is it happening that a different thread is able to see updates made by the main thread without any explicit synchronization?
class Counter {
public:
int count = 0;
}
void print(Counter* counter) {
std::cout << counter.count;
}
int main() {
Counter* cPtr = new Counter();
cPtr->count = 10;
pThread = new std::thread(print, cPtr);
// Assume that the program does not quit until the above
// thread has finished.
pThread->join();
}
Another e.g. from folly
documentation:
EventBase base;
auto thread = std::thread([&](){
base.loopForever();
});
base
is being used in a different thread. How is it ensured that that thread sees all the initialized fields of base
object correctly?
Apologies if this question sound too basic but I wasn't able to find an answer.