Roc Toolkit internal modules
Roc Toolkit: real-time audio streaming
Loading...
Searching...
No Matches
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"
20#include "roc_core/panic.h"
21
22namespace roc {
23namespace core {
24
25//! Singleton.
26template <class T> class Singleton : public NonCopyable<> {
27public:
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
38 return *inst;
39 }
40
41private:
42 static void create_() {
43 T* inst = new (storage_.memory()) T;
45 }
46
47 static pthread_once_t once_;
48 static AlignedStorage<sizeof(T)> storage_;
49 static T* instance_;
50};
51
52//! @cond HIDDEN
53template <class T> pthread_once_t Singleton<T>::once_ = PTHREAD_ONCE_INIT;
54template <class T> AlignedStorage<sizeof(T)> Singleton<T>::storage_;
55template <class T> T* Singleton<T>::instance_;
56//! @endcond
57
58} // namespace core
59} // namespace roc
60
61#endif // ROC_CORE_SINGLETON_H_
Aligned storage.
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
Shared ownership intrusive pointer.
Definition shared_ptr.h:32
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