refcount.h 8.1 KB
Newer Older
Kenton Varda's avatar
Kenton Varda committed
1 2
// Copyright (c) 2013-2014 Sandstorm Development Group, Inc. and contributors
// Licensed under the MIT License:
Kenton Varda's avatar
Kenton Varda committed
3
//
Kenton Varda's avatar
Kenton Varda committed
4 5 6 7 8 9
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
Kenton Varda's avatar
Kenton Varda committed
10
//
Kenton Varda's avatar
Kenton Varda committed
11 12
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
Kenton Varda's avatar
Kenton Varda committed
13
//
Kenton Varda's avatar
Kenton Varda committed
14 15 16 17 18 19 20
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
Kenton Varda's avatar
Kenton Varda committed
21

22
#pragma once
Kenton Varda's avatar
Kenton Varda committed
23

24 25
#include "memory.h"

26 27 28 29
#if defined(__GNUC__) && !KJ_HEADER_WARNINGS
#pragma GCC system_header
#endif

30
#if _MSC_VER
31 32 33
#if _MSC_VER < 1910
#include <intrin.h>
#else
34 35
#include <intrin0.h>
#endif
36
#endif
37

Kenton Varda's avatar
Kenton Varda committed
38 39
namespace kj {

40 41 42
// =======================================================================================
// Non-atomic (thread-unsafe) refcounting

Kenton Varda's avatar
Kenton Varda committed
43
class Refcounted: private Disposer {
David Renshaw's avatar
David Renshaw committed
44
  // Subclass this to create a class that contains a reference count. Then, use
Kenton Varda's avatar
Kenton Varda committed
45 46 47
  // `kj::refcounted<T>()` to allocate a new refcounted pointer.
  //
  // Do NOT use this lightly.  Refcounting is a crutch.  Good designs should strive to make object
48 49 50 51 52 53
  // ownership clear, so that refcounting is not necessary.  All that said, reference counting can
  // sometimes simplify code that would otherwise become convoluted with explicit ownership, even
  // when ownership relationships are clear at an abstract level.
  //
  // NOT THREADSAFE:  This refcounting implementation assumes that an object's references are
  // manipulated only in one thread, because atomic (thread-safe) refcounting is surprisingly slow.
Kenton Varda's avatar
Kenton Varda committed
54 55
  //
  // In general, abstract classes should _not_ subclass this.  The concrete class at the bottom
David Renshaw's avatar
David Renshaw committed
56
  // of the hierarchy should be the one to decide how it implements refcounting.  Interfaces should
Kenton Varda's avatar
Kenton Varda committed
57 58 59 60 61 62 63
  // expose only an `addRef()` method that returns `Own<InterfaceType>`.  There are two reasons for
  // this rule:
  // 1. Interfaces would need to virtually inherit Refcounted, otherwise two refcounted interfaces
  //    could not be inherited by the same subclass.  Virtual inheritance is awkward and
  //    inefficient.
  // 2. An implementation may decide that it would rather return a copy than a refcount, or use
  //    some other strategy.
64 65 66 67
  //
  // TODO(cleanup):  Rethink above.  Virtual inheritance is not necessarily that bad.  OTOH, a
  //   virtual function call for every refcount is sad in its own way.  A Ref<T> type to replace
  //   Own<T> could also be nice.
Kenton Varda's avatar
Kenton Varda committed
68 69

public:
70
  Refcounted() = default;
Kenton Varda's avatar
Kenton Varda committed
71
  virtual ~Refcounted() noexcept(false);
72
  KJ_DISALLOW_COPY(Refcounted);
Kenton Varda's avatar
Kenton Varda committed
73

74 75 76 77
  inline bool isShared() const { return refcount > 1; }
  // Check if there are multiple references to this object. This is sometimes useful for deciding
  // whether it's safe to modify the object vs. make a copy.

Kenton Varda's avatar
Kenton Varda committed
78
private:
79 80
  mutable uint refcount = 0;
  // "mutable" because disposeImpl() is const.  Bleh.
Kenton Varda's avatar
Kenton Varda committed
81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111

  void disposeImpl(void* pointer) const override;
  template <typename T>
  static Own<T> addRefInternal(T* object);

  template <typename T>
  friend Own<T> addRef(T& object);
  template <typename T, typename... Params>
  friend Own<T> refcounted(Params&&... params);
};

template <typename T, typename... Params>
inline Own<T> refcounted(Params&&... params) {
  // Allocate a new refcounted instance of T, passing `params` to its constructor.  Returns an
  // initial reference to the object.  More references can be created with `kj::addRef()`.

  return Refcounted::addRefInternal(new T(kj::fwd<Params>(params)...));
}

template <typename T>
Own<T> addRef(T& object) {
  // Return a new reference to `object`, which must subclass Refcounted and have been allocated
  // using `kj::refcounted<>()`.  It is suggested that subclasses implement a non-static addRef()
  // method which wraps this and returns the appropriate type.

  KJ_IREQUIRE(object.Refcounted::refcount > 0, "Object not allocated with kj::refcounted().");
  return Refcounted::addRefInternal(&object);
}

template <typename T>
Own<T> Refcounted::addRefInternal(T* object) {
112 113
  Refcounted* refcounted = object;
  ++refcounted->refcount;
Kenton Varda's avatar
Kenton Varda committed
114 115 116
  return Own<T>(object, *refcounted);
}

117 118 119 120 121
// =======================================================================================
// Atomic (thread-safe) refcounting
//
// Warning: Atomic ops are SLOW.

122 123 124 125 126 127 128 129
#if _MSC_VER
#if _M_ARM
#define KJ_MSVC_INTERLOCKED(OP, MEM) _Interlocked##OP##_##MEM
#else
#define KJ_MSVC_INTERLOCKED(OP, MEM) _Interlocked##OP
#endif
#endif

130 131
class AtomicRefcounted: private kj::Disposer {
public:
132
  AtomicRefcounted() = default;
133
  virtual ~AtomicRefcounted() noexcept(false);
134
  KJ_DISALLOW_COPY(AtomicRefcounted);
135

136 137
  inline bool isShared() const {
#if _MSC_VER
138
    return KJ_MSVC_INTERLOCKED(Or, acq)(&refcount, 0) > 1;
139 140 141 142
#else
    return __atomic_load_n(&refcount, __ATOMIC_ACQUIRE) > 1;
#endif
  }
143 144

private:
145 146 147 148 149
#if _MSC_VER
  mutable volatile long refcount = 0;
#else
  mutable volatile uint refcount = 0;
#endif
150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205

  bool addRefWeakInternal() const;

  void disposeImpl(void* pointer) const override;
  template <typename T>
  static kj::Own<T> addRefInternal(T* object);
  template <typename T>
  static kj::Own<const T> addRefInternal(const T* object);

  template <typename T>
  friend kj::Own<T> atomicAddRef(T& object);
  template <typename T>
  friend kj::Own<const T> atomicAddRef(const T& object);
  template <typename T>
  friend kj::Maybe<kj::Own<const T>> atomicAddRefWeak(const T& object);
  template <typename T, typename... Params>
  friend kj::Own<T> atomicRefcounted(Params&&... params);
};

template <typename T, typename... Params>
inline kj::Own<T> atomicRefcounted(Params&&... params) {
  return AtomicRefcounted::addRefInternal(new T(kj::fwd<Params>(params)...));
}

template <typename T>
kj::Own<T> atomicAddRef(T& object) {
  KJ_IREQUIRE(object.AtomicRefcounted::refcount > 0, "Object not allocated with kj::refcounted().");
  return AtomicRefcounted::addRefInternal(&object);
}

template <typename T>
kj::Own<const T> atomicAddRef(const T& object) {
  KJ_IREQUIRE(object.AtomicRefcounted::refcount > 0, "Object not allocated with kj::refcounted().");
  return AtomicRefcounted::addRefInternal(&object);
}

template <typename T>
kj::Maybe<kj::Own<const T>> atomicAddRefWeak(const T& object) {
  // Try to addref an object whose refcount could have already reached zero in another thread, and
  // whose destructor could therefore already have started executing. The destructor must contain
  // some synchronization that guarantees that said destructor has not yet completed when
  // attomicAddRefWeak() is called (so that the object is still valid). Since the destructor cannot
  // be canceled once it has started, in the case that it has already started, this function
  // returns nullptr.

  const AtomicRefcounted* refcounted = &object;
  if (refcounted->addRefWeakInternal()) {
    return kj::Own<const T>(&object, *refcounted);
  } else {
    return nullptr;
  }
}

template <typename T>
kj::Own<T> AtomicRefcounted::addRefInternal(T* object) {
  AtomicRefcounted* refcounted = object;
206 207 208
#if _MSC_VER
  KJ_MSVC_INTERLOCKED(Increment, nf)(&refcounted->refcount);
#else
209
  __atomic_add_fetch(&refcounted->refcount, 1, __ATOMIC_RELAXED);
210
#endif
211 212 213 214 215 216
  return kj::Own<T>(object, *refcounted);
}

template <typename T>
kj::Own<const T> AtomicRefcounted::addRefInternal(const T* object) {
  const AtomicRefcounted* refcounted = object;
217 218 219
#if _MSC_VER
  KJ_MSVC_INTERLOCKED(Increment, nf)(&refcounted->refcount);
#else
220
  __atomic_add_fetch(&refcounted->refcount, 1, __ATOMIC_RELAXED);
221
#endif
222 223 224
  return kj::Own<const T>(object, *refcounted);
}

Kenton Varda's avatar
Kenton Varda committed
225
}  // namespace kj