Question

I have a class which contains a BYTE*, a reference counter and a CRITICAL_SECTION which protects both of them from concurrent access.

I wanna replace all that with a std::tr1::shared_ptr<BYTE>. The MSDN says that:

Multiple threads can read and write different shared_ptr objects at the same time, even when the objects are copies that share ownership.

Everything sounds alright, until I find out that the CRITICAL_SECTION from the class is used outside of it to "lock" it and alter its contents in a mutually exclusive fashion. Okay, it's breaks encapsulation, I wanna change that.

I know shared_ptr guarantees that the memory will be freed, but does it guarantee mutual exclusion when you write to the memory?

Was it helpful?

Solution

It is up to you to ensure correct access to the data the std::tr1::shared_ptr points to. That data is yours. It only matters to the std::tr1::shared_ptr when it's time to delete it.

Regarding the std::tr1::shared_ptr object itself, you have the following guarantees:

  • you can safely read from the same instance from multiple threads;
  • you can safely mutate different instances of shared_ptr from multiple threads, even when the instances are copies (sharing the same reference count or whatever);

Any other simultaneous access (like reading and writing simultaneously to the same instance) is undefined behaviour.

Also note that the shared_ptr in the new C++11 standard has a special API for atomic access.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top