问题
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