joshualitt | 2419b36 | 2015-07-13 09:29:42 -0700 | [diff] [blame] | 1 | /* |
| 2 | * Copyright 2015 Google Inc. |
| 3 | * |
| 4 | * Use of this source code is governed by a BSD-style license that can be |
| 5 | * found in the LICENSE file. |
| 6 | */ |
| 7 | |
| 8 | #ifndef GrNonAtomicRef_DEFINED |
| 9 | #define GrNonAtomicRef_DEFINED |
| 10 | |
Ben Wagner | d5148e3 | 2018-07-16 17:44:06 -0400 | [diff] [blame] | 11 | #include "SkNoncopyable.h" |
joshualitt | 2419b36 | 2015-07-13 09:29:42 -0700 | [diff] [blame] | 12 | #include "SkRefCnt.h" |
| 13 | #include "SkTArray.h" |
| 14 | |
| 15 | /** |
| 16 | * A simple non-atomic ref used in the GrBackend when we don't want to pay for the overhead of a |
| 17 | * threadsafe ref counted object |
| 18 | */ |
cdalton | 4833f39 | 2016-02-02 22:46:16 -0800 | [diff] [blame] | 19 | template<typename TSubclass> class GrNonAtomicRef : public SkNoncopyable { |
joshualitt | 2419b36 | 2015-07-13 09:29:42 -0700 | [diff] [blame] | 20 | public: |
| 21 | GrNonAtomicRef() : fRefCnt(1) {} |
cdalton | 4833f39 | 2016-02-02 22:46:16 -0800 | [diff] [blame] | 22 | |
| 23 | #ifdef SK_DEBUG |
| 24 | ~GrNonAtomicRef() { |
joshualitt | 2419b36 | 2015-07-13 09:29:42 -0700 | [diff] [blame] | 25 | // fRefCnt can be one when a subclass is created statically |
| 26 | SkASSERT((0 == fRefCnt || 1 == fRefCnt)); |
| 27 | // Set to invalid values. |
cdalton | 4833f39 | 2016-02-02 22:46:16 -0800 | [diff] [blame] | 28 | fRefCnt = -10; |
joshualitt | 2419b36 | 2015-07-13 09:29:42 -0700 | [diff] [blame] | 29 | } |
cdalton | 4833f39 | 2016-02-02 22:46:16 -0800 | [diff] [blame] | 30 | #endif |
joshualitt | 2419b36 | 2015-07-13 09:29:42 -0700 | [diff] [blame] | 31 | |
csmartdalton | 28341fa | 2016-08-17 10:00:21 -0700 | [diff] [blame] | 32 | bool unique() const { return 1 == fRefCnt; } |
| 33 | |
joshualitt | 2419b36 | 2015-07-13 09:29:42 -0700 | [diff] [blame] | 34 | void ref() const { |
| 35 | // Once the ref cnt reaches zero it should never be ref'ed again. |
| 36 | SkASSERT(fRefCnt > 0); |
| 37 | ++fRefCnt; |
| 38 | } |
| 39 | |
| 40 | void unref() const { |
| 41 | SkASSERT(fRefCnt > 0); |
| 42 | --fRefCnt; |
| 43 | if (0 == fRefCnt) { |
cdalton | 4833f39 | 2016-02-02 22:46:16 -0800 | [diff] [blame] | 44 | GrTDeleteNonAtomicRef(static_cast<const TSubclass*>(this)); |
joshualitt | 2419b36 | 2015-07-13 09:29:42 -0700 | [diff] [blame] | 45 | return; |
| 46 | } |
| 47 | } |
| 48 | |
| 49 | private: |
| 50 | mutable int32_t fRefCnt; |
| 51 | |
| 52 | typedef SkNoncopyable INHERITED; |
| 53 | }; |
| 54 | |
cdalton | 4833f39 | 2016-02-02 22:46:16 -0800 | [diff] [blame] | 55 | template<typename T> inline void GrTDeleteNonAtomicRef(const T* ref) { |
| 56 | delete ref; |
| 57 | } |
| 58 | |
joshualitt | 2419b36 | 2015-07-13 09:29:42 -0700 | [diff] [blame] | 59 | #endif |