Thrill  0.1
singleton.hpp
Go to the documentation of this file.
1 /*******************************************************************************
2  * thrill/common/singleton.hpp
3  *
4  * Copied and modified from STXXL https://github.com/stxxl/stxxl, which is
5  * distributed under the Boost Software License, Version 1.0.
6  *
7  * Part of Project Thrill - http://project-thrill.org
8  *
9  * Copyright (C) 2002-2004 Roman Dementiev <[email protected]>
10  * Copyright (C) 2008-2010 Andreas Beckmann <[email protected]>
11  * Copyright (C) 2009, 2010 Johannes Singler <[email protected]>
12  *
13  * All rights reserved. Published under the BSD-2 license in the LICENSE file.
14  ******************************************************************************/
15 
16 #pragma once
17 #ifndef THRILL_COMMON_SINGLETON_HEADER
18 #define THRILL_COMMON_SINGLETON_HEADER
19 
20 #include <cstdlib>
21 #include <mutex>
22 
23 namespace thrill {
24 namespace common {
25 
26 template <typename Instance, bool destroy_on_exit = true>
27 class Singleton
28 {
29  using instance_type = Instance;
32 
34 
36  static void DestroyInstance();
37 
38 public:
39  Singleton() = default;
40 
41  //! non-copyable: delete copy-constructor
42  Singleton(const Singleton&) = delete;
43  //! non-copyable: delete assignment operator
44  Singleton& operator = (const Singleton&) = delete;
45  //! move-constructor: default
46  Singleton(Singleton&&) = default;
47  //! move-assignment operator: default
48  Singleton& operator = (Singleton&&) = default;
49 
50  inline static instance_pointer GetInstance() {
51  if (!instance_)
52  return CreateInstance();
53 
54  return instance_;
55  }
56 };
57 
58 template <typename Instance, bool destroy_on_exit>
61  static std::mutex create_mutex;
62  std::unique_lock<std::mutex> lock(create_mutex);
63  if (!instance_) {
64  instance_ = new instance_type();
65  if (destroy_on_exit)
66  atexit(DestroyInstance);
67  }
68  return instance_;
69 }
70 
71 template <typename Instance, bool destroy_on_exit>
74  // instance = nullptr;
75  instance_ = reinterpret_cast<instance_pointer>(size_t(-1)); // bomb if used again
76  delete inst;
77 }
78 
79 template <typename Instance, bool destroy_on_exit>
82 
83 } // namespace common
84 } // namespace thrill
85 
86 #endif // !THRILL_COMMON_SINGLETON_HEADER
87 
88 /******************************************************************************/
static volatile_instance_pointer instance_
Definition: singleton.hpp:33
volatile instance_pointer volatile_instance_pointer
Definition: singleton.hpp:31
instance_type * instance_pointer
Definition: singleton.hpp:30
static instance_pointer CreateInstance()
Definition: singleton.hpp:60
static instance_pointer GetInstance()
Definition: singleton.hpp:50
Singleton & operator=(const Singleton &)=delete
non-copyable: delete assignment operator
static void DestroyInstance()
Definition: singleton.hpp:72