Shared_ptr and Memory Visibility in c++

空扰寡人 提交于 2019-12-06 13:27:25

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.

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

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