Shared_ptr and Memory Visibility in c++

大兔子大兔子 提交于 2019-12-22 12:39:09

问题


If you heap allocate an object with shared_ptr on thread A , then copy the shared_ptr to another thread without any synchronization. Is the other thread guaranteed to see a fully constructed object?

int main(){
    auto sp = std::make_shared<int>(5);
    auto f=std::async(std::launch::async, [sp](){
    std::cout<<*sp;});
}

Is it guaranteed to print 5?


回答1:


In your example, the shared_ptr object has been duplicated before std::async returns, hence it still exists in the new thread even if the original shared_ptr is destroyed before the second thread accesses it's copy.

So, the answer is yes. You are passing by value, hence a copy.




回答2:


As someone already pointed out in the comment, your specific scenario above (heap allocated object is accessed via a pointer passed to a newly spawned thread via thread arg) is covered by the answer to this question.

Now for the scenario described in your follow-up question (heap allocated object is accessed in a separate thread via pointer pushed to a queue), the worker thread is guaranteed to see '5' because the queue has to be implemented in a thread safe fashion whereby memory barrier ensures the visibility of the value stored in the heap object (in your case, mutex uses memory barrier behind the scene).



来源:https://stackoverflow.com/questions/56679102/shared-ptr-and-memory-visibility-in-c

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