A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://stackoverflow.com/questions/43297517/stdshared-ptr-internals-weak-count-more-than-expected below:

c++ - std::shared_ptr internals, weak count more than expected

Imagine the following scenario. Thread A holds a shared_ptr, thread B holds a corresponding weak_ptr. So in your implementation, we have _Uses == 1 and _Weaks == 1.

There are two possible implementations for the smart pointer destructors, both with problems.

Implementation 1: decrement, then check

B's weak_ptr is destroyed. Decrements _Weaks. We have _Uses == 1, _Weaks == 0. B prepares to check _Uses, but ...

Context switch.

A's shared_ptr is destroyed. Decrements _Uses. We have _Uses == 0, _Weaks == 0. Begin destruction of _Ref_count.

Context switch.

B now get round to checking _Uses. It's 0. Begin destruction of _Ref_count.

Both threads are now in the process of destroying _Ref_count. Not good.

Implementation 2: check, then decrement

B's weak_ptr is destroyed. Check _Uses. It's 1, no destruction will happen. B prepares to decrement _Weaks, but ...

Contex switch.

A's shared_ptr is destroyed. Checks _Weaks. It's 1, no destruction will happen. Decrement _Uses. We have _Uses == 0, _Weaks == 1. Done.

Context switch.

B now gets round to decrement _Weaks. We have _Uses == 0, _Weaks == 0. Nothing else to do.

We have leaked the _Ref_count. Not good.


RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4