STXXL  1.4-dev
 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 
24 
25 template <typename INSTANCE, bool destroy_on_exit = true>
26 class singleton : private noncopyable
27 {
28  typedef INSTANCE instance_type;
31 
32  static volatile_instance_pointer instance;
33 
34  static instance_pointer create_instance();
35  static void destroy_instance();
36 
37 public:
39  {
40  if (!instance)
41  return create_instance();
42 
43  return instance;
44  }
45 };
46 
47 template <typename INSTANCE, bool destroy_on_exit>
48 typename singleton<INSTANCE, destroy_on_exit>::instance_pointer
50 {
51  static mutex create_mutex;
52  scoped_mutex_lock instance_write_lock(create_mutex);
53  if (!instance) {
54  instance = new instance_type();
55  if (destroy_on_exit)
56  register_exit_handler(destroy_instance);
57  }
58  return instance;
59 }
60 
61 template <typename INSTANCE, bool destroy_on_exit>
63 {
64  instance_pointer inst = instance;
65  //instance = NULL;
66  instance = reinterpret_cast<instance_pointer>(unsigned_type(-1)); // bomb if used again
67  delete inst;
68 }
69 
70 template <typename INSTANCE, bool destroy_on_exit>
73 
75 
76 #endif // !STXXL_SINGLETON_HEADER
INSTANCE instance_type
Definition: singleton.h:28
instance_type * instance_pointer
Definition: singleton.h:29
static instance_pointer get_instance()
Definition: singleton.h:38
Aquire a lock that&#39;s valid until the end of scope.
Definition: mutex.h:123
#define STXXL_BEGIN_NAMESPACE
Definition: namespace.h:16
choose_int_types< my_pointer_size >::unsigned_type unsigned_type
Definition: types.h:64
int register_exit_handler(void(*function)(void))
Definition: exithandler.cpp:28
volatile instance_pointer volatile_instance_pointer
Definition: singleton.h:30
static volatile_instance_pointer instance
Definition: singleton.h:32
#define STXXL_END_NAMESPACE
Definition: namespace.h:17