summaryrefslogtreecommitdiff
path: root/Runtime/Threads/AtomicRefCounter.h
blob: 9e6b5e7a2903e806d3509151b9bb58773bdb8eba (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#ifndef __UNITY_ATOMIC_REFCOUNTER_H
#define __UNITY_ATOMIC_REFCOUNTER_H

#include "AtomicOps.h"

// Used for threadsafe refcounting
class AtomicRefCounter {
private:
	volatile int m_Counter;
public:
	// Upon the construction the self-counter is always set to 1,
	// which means that this instance is already accounted for.
	// This scheme shaves off the cycles that would be consumed
	// during the unavoidable first Retain call otherwise.
	AtomicRefCounter() : m_Counter(1) {}
	
	FORCE_INLINE void Retain ()
	{
		AtomicIncrement(&m_Counter);
	}

	FORCE_INLINE bool Release ()
	{
		int afterDecrement = AtomicDecrement(&m_Counter);
		AssertIf( afterDecrement < 0 ); // If we hit this assert, someone is Releasing without matching it with Retain
		return afterDecrement == 0;
	}
};

#endif // __UNITY_ATOMIC_REFCOUNTER_H