1// Copyright (c) 2011 The Chromium Authors. All rights reserved. 2// Use of this source code is governed by a BSD-style license that can be 3// found in the LICENSE file. 4 5// This is a low level implementation of atomic semantics for reference 6// counting. Please use base/memory/ref_counted.h directly instead. 7// 8// The implementation includes annotations to avoid some false positives 9// when using data race detection tools. 10 11#ifndef BASE_ATOMIC_REF_COUNT_H_ 12#define BASE_ATOMIC_REF_COUNT_H_ 13 14#include "base/atomicops.h" 15 16namespace base { 17 18typedef subtle::Atomic32 AtomicRefCount; 19 20// Increment a reference count by "increment", which must exceed 0. 21inline void AtomicRefCountIncN(volatile AtomicRefCount *ptr, 22 AtomicRefCount increment) { 23 subtle::NoBarrier_AtomicIncrement(ptr, increment); 24} 25 26// Decrement a reference count by "decrement", which must exceed 0, 27// and return whether the result is non-zero. 28// Insert barriers to ensure that state written before the reference count 29// became zero will be visible to a thread that has just made the count zero. 30inline bool AtomicRefCountDecN(volatile AtomicRefCount *ptr, 31 AtomicRefCount decrement) { 32 bool res = (subtle::Barrier_AtomicIncrement(ptr, -decrement) != 0); 33 return res; 34} 35 36// Increment a reference count by 1. 37inline void AtomicRefCountInc(volatile AtomicRefCount *ptr) { 38 base::AtomicRefCountIncN(ptr, 1); 39} 40 41// Decrement a reference count by 1 and return whether the result is non-zero. 42// Insert barriers to ensure that state written before the reference count 43// became zero will be visible to a thread that has just made the count zero. 44inline bool AtomicRefCountDec(volatile AtomicRefCount *ptr) { 45 return base::AtomicRefCountDecN(ptr, 1); 46} 47 48// Return whether the reference count is one. If the reference count is used 49// in the conventional way, a refrerence count of 1 implies that the current 50// thread owns the reference and no other thread shares it. This call performs 51// the test for a reference count of one, and performs the memory barrier 52// needed for the owning thread to act on the object, knowing that it has 53// exclusive access to the object. 54inline bool AtomicRefCountIsOne(volatile AtomicRefCount *ptr) { 55 bool res = (subtle::Acquire_Load(ptr) == 1); 56 return res; 57} 58 59// Return whether the reference count is zero. With conventional object 60// referencing counting, the object will be destroyed, so the reference count 61// should never be zero. Hence this is generally used for a debug check. 62inline bool AtomicRefCountIsZero(volatile AtomicRefCount *ptr) { 63 bool res = (subtle::Acquire_Load(ptr) == 0); 64 return res; 65} 66 67} // namespace base 68 69#endif // BASE_ATOMIC_REF_COUNT_H_ 70