Line data Source code
1 : // 2 : // immer: immutable data structures for C++ 3 : // Copyright (C) 2016, 2017, 2018 Juan Pedro Bolivar Puente 4 : // 5 : // This software is distributed under the Boost Software License, Version 1.0. 6 : // See accompanying file LICENSE or copy at http://boost.org/LICENSE_1_0.txt 7 : // 8 : 9 : #pragma once 10 : 11 : #include <immer/refcount/no_refcount_policy.hpp> 12 : 13 : #include <atomic> 14 : #include <cassert> 15 : #include <utility> 16 : 17 : namespace immer { 18 : 19 : /*! 20 : * A reference counting policy implemented using an *atomic* `int` 21 : * count. It is **thread-safe**. 22 : */ 23 : struct refcount_policy 24 : { 25 : mutable std::atomic<int> refcount; 26 : 27 66954 : refcount_policy() 28 30239 : : refcount{1} {}; 29 : refcount_policy(disowned) 30 : : refcount{0} 31 : {} 32 : 33 1583384 : void inc() { refcount.fetch_add(1, std::memory_order_relaxed); } 34 : 35 35321 : bool dec() { return 1 == refcount.fetch_sub(1, std::memory_order_acq_rel); } 36 : 37 5297 : void dec_unsafe() 38 : { 39 5297 : assert(refcount.load() > 1); 40 5297 : refcount.fetch_sub(1, std::memory_order_relaxed); 41 5297 : } 42 : 43 : bool unique() { return refcount == 1; } 44 : }; 45 : 46 : } // namespace immer