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

半腔热情 提交于 2021-01-28 01:26:14

问题


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.


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/60202283/memory-visibility-when-a-pointer-to-an-object-is-passed-to-stdthread-as-argume

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!