Using shared_ptr across thread

  • Thread starter Thread starter Andrew Ch. _
  • Start date Start date
A

Andrew Ch. _

Guest
I am in a situation where I need the life time of an object to last until at least as long as a callback function is called (which will be called in a separate thread -- I have no control over this). I was thinking of using a shared_ptr to ensure this, but am not sure how they behave when their count is modified across threads. This is not my real life example but consider the following:


...
{
shared_ptr<Thing> MyThing = new Thing() ;

std::async( [MyThing]()mutable
{
// MyThing is a local copy within the running lambda in this thread.

// Do some stuff
...

// We are finished with our copy of the shared_ptr.
// This is actually superfluous, as it will go out of scope
// but I add it to emphasise that the count will be reduced.
MyThing.reset() ;
} ) ;


// Main thread continues
...

// The shared_ptr in the main thread goes out of scope, so the count
// will reduce.
}

// Main thread continues after its MyThing is out of scope
...




Apart from the fact that I need to be careful about how the "Thing" object itself is used in the main thread and in the spawned thread, is the use of the shared_ptr like this safe?

My concern is that at some point the shared_ptr counter will be reduced in both the main thread and in the spawned thread and I do not know if this is handled safely in shared_ptr. Are there other considerations I need to think about as well?

If this is not safe, are there any patterns of use that are safe?

Thanks in advance,

Andrew Ch

Continue reading...
 
Back
Top