Roc Toolkit internal modules
Roc Toolkit: real-time audio streaming
singleton.h
Go to the documentation of this file.
1 /*
2  * Copyright (c) 2017 Roc Streaming authors
3  *
4  * This Source Code Form is subject to the terms of the Mozilla Public
5  * License, v. 2.0. If a copy of the MPL was not distributed with this
6  * file, You can obtain one at http://mozilla.org/MPL/2.0/.
7  */
8 
9 //! @file roc_core/target_posix/roc_core/singleton.h
10 //! @brief Singleton.
11 
12 #ifndef ROC_CORE_SINGLETON_H_
13 #define ROC_CORE_SINGLETON_H_
14 
15 #include <pthread.h>
16 
18 #include "roc_core/atomic_ops.h"
19 #include "roc_core/noncopyable.h"
20 #include "roc_core/panic.h"
21 
22 namespace roc {
23 namespace core {
24 
25 //! Singleton.
26 template <class T> class Singleton : public NonCopyable<> {
27 public:
28  //! Get singleton instance.
29  static T& instance() {
30  T* inst = AtomicOps::load_relaxed(instance_);
31 
32  if (!inst) {
33  pthread_once(&once_, create_);
34  inst = AtomicOps::load_relaxed(instance_);
35  }
36 
37  roc_panic_if_not(inst);
38  return *inst;
39  }
40 
41 private:
42  static void create_() {
43  T* inst = new (storage_.memory()) T;
44  AtomicOps::store_release(instance_, inst);
45  }
46 
47  static pthread_once_t once_;
48  static AlignedStorage<sizeof(T)> storage_;
49  static T* instance_;
50 };
51 
52 template <class T> pthread_once_t Singleton<T>::once_ = PTHREAD_ONCE_INIT;
53 template <class T> AlignedStorage<sizeof(T)> Singleton<T>::storage_;
54 template <class T> T* Singleton<T>::instance_;
55 
56 } // namespace core
57 } // namespace roc
58 
59 #endif // ROC_CORE_SINGLETON_H_
Aligned storage.
const void * memory() const
Get storage memory.
static T load_relaxed(const T &var)
Atomic load (no barrier).
Definition: atomic_ops.h:46
static void store_release(T1 &var, T2 val)
Atomic store (release barrier).
Definition: atomic_ops.h:71
Base class for non-copyable objects.
Definition: noncopyable.h:23
static T & instance()
Get singleton instance.
Definition: singleton.h:29
Root namespace.
Non-copyable object.
Panic.
#define roc_panic_if_not(x)
Panic if condition is false.
Definition: panic.h:37