STXXL  1.4.0
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Groups Pages
singleton.h
Go to the documentation of this file.
1 /***************************************************************************
2  * include/stxxl/bits/singleton.h
3  *
4  * Part of the STXXL. See http://stxxl.sourceforge.net
5  *
6  * Copyright (C) 2008, 2011 Andreas Beckmann <[email protected]>
7  *
8  * Distributed under the Boost Software License, Version 1.0.
9  * (See accompanying file LICENSE_1_0.txt or copy at
10  * http://www.boost.org/LICENSE_1_0.txt)
11  **************************************************************************/
12 
13 #ifndef STXXL_SINGLETON_HEADER
14 #define STXXL_SINGLETON_HEADER
15 
16 #include <cstdlib>
17 
18 #include <stxxl/types>
19 #include <stxxl/bits/noncopyable.h>
22 
23 
25 
26 template <typename INSTANCE, bool destroy_on_exit = true>
27 class singleton : private noncopyable
28 {
29  typedef INSTANCE instance_type;
32 
33  static volatile_instance_pointer instance;
34 
35  static instance_pointer create_instance();
36  static void destroy_instance();
37 
38 public:
40  {
41  if (!instance)
42  return create_instance();
43 
44  return instance;
45  }
46 };
47 
48 template <typename INSTANCE, bool destroy_on_exit>
49 typename singleton<INSTANCE, destroy_on_exit>::instance_pointer
51 {
52  static mutex create_mutex;
53  scoped_mutex_lock instance_write_lock(create_mutex);
54  if (!instance) {
55  instance = new instance_type();
56  if (destroy_on_exit)
57  register_exit_handler(destroy_instance);
58  }
59  return instance;
60 }
61 
62 template <typename INSTANCE, bool destroy_on_exit>
64 {
65  instance_pointer inst = instance;
66  //instance = NULL;
67  instance = reinterpret_cast<instance_pointer>(unsigned_type(-1)); // bomb if used again
68  delete inst;
69 }
70 
71 template <typename INSTANCE, bool destroy_on_exit>
74 
76 
77 #endif // !STXXL_SINGLETON_HEADER
INSTANCE instance_type
Definition: singleton.h:29
Encapsulates disk queues.
Definition: disk_queues.h:34
instance_type * instance_pointer
Definition: singleton.h:30
static instance_pointer get_instance()
Definition: singleton.h:39
Aquire a lock that&#39;s valid until the end of scope.
Definition: mutex.h:106
#define STXXL_BEGIN_NAMESPACE
Definition: namespace.h:16
choose_int_types< my_pointer_size >::unsigned_type unsigned_type
Definition: types.h:67
int register_exit_handler(void(*function)(void))
Definition: exithandler.cpp:29
volatile instance_pointer volatile_instance_pointer
Definition: singleton.h:31
static volatile_instance_pointer instance
Definition: singleton.h:33
#define STXXL_END_NAMESPACE
Definition: namespace.h:17