BooObject: Make atomic ordering constraints less strict

Increasing a reference count is able to always be relaxed. New
references to an object can only be formed from an existing reference.
The passing of an existing reference from one thread to another will
already necessitate the use of synchronization primitives, so this is a
safe change to make. Regardless, nothing other than the object itself
directly relies on the reference count, so this will always be a
suitably atomic operation, even in the face of no synchronization
primitives.

In the case of decrementing the reference count, it's sufficient to
treat it with release semantics and follow it up with an atomic thread
fence. This ensures that all accesses to the object in one thread will
occur before the delete occurs in another thread (if the situation ever
occurs).

This should make for a slightly more efficient increment and decrement.
This commit is contained in:
Lioncash 2019-08-17 12:59:37 -04:00
parent c33604b8cb
commit 4d91a1b3c3
1 changed files with 3 additions and 2 deletions

View File

@ -14,9 +14,10 @@ protected:
public: public:
virtual std::unique_lock<std::recursive_mutex> destructorLock() = 0; virtual std::unique_lock<std::recursive_mutex> destructorLock() = 0;
void increment() { m_refCount++; } void increment() { m_refCount.fetch_add(1, std::memory_order_relaxed); }
void decrement() { void decrement() {
if (m_refCount.fetch_sub(1) == 1) { if (m_refCount.fetch_sub(1, std::memory_order_acq_rel) == 1) {
std::atomic_thread_fence(std::memory_order_acquire);
auto lk = destructorLock(); auto lk = destructorLock();
delete this; delete this;
} }