开发者

Does std::tr1::shared_ptr do mutual exclusion?

开发者 https://www.devze.com 2023-03-31 01:42 出处:网络
I have a class which contains a BYTE*, a reference counter and a CRITICAL_SECTION which protects both of them from concurrent access.

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 wr开发者_Python百科ite to the memory?


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号