简体   繁体   中英

Memory visibility when a pointer to an object is passed to std::thread as argument

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 eg 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.

Synchronization doesn't mean "update" for the parameter. If you have a variable shared between threads and this variable is set to a value from a thread, all the other threads will see the same value.

Synchronzation is about knowning or expecting the change of the value. If you have a thread that sets a variable, other threads must not attempt to set it at the same time for example or this will lead to UD on the variable's actual value.

But, since all threads share the same memory, "updating" the value is not needed.

Variable V. Thread A sets V to 1. Thread B reads V after being set by A, it will have the value of 1. The question is when Thread B should read the variable (that is, after A has set it) - that's the point of synchronization.

There is no need a mechanism which makes the int count; visible to other threads because it just resides on memory, pointer says the address of the resource so anything who has a pointer to the int count can see what resides in it ( there could be some special cases ). So it is natural and comes free.

Syncronization is a different topic and it is not made to see updates immediately. It is generally made to access/update the resources in synchronized to prevent creating race conditions, etc.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM