libmesh_singleton.C
Go to the documentation of this file.
1 // The libMesh Finite Element Library.
2 // Copyright (C) 2002-2013 Benjamin S. Kirk, John W. Peterson, Roy H. Stogner
3 
4 // This library is free software; you can redistribute it and/or
5 // modify it under the terms of the GNU Lesser General Public
6 // License as published by the Free Software Foundation; either
7 // version 2.1 of the License, or (at your option) any later version.
8 
9 // This library is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 // Lesser General Public License for more details.
13 
14 // You should have received a copy of the GNU Lesser General Public
15 // License along with this library; if not, write to the Free Software
16 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
17 
18 
19 
20 // Local includes
22 #include "libmesh/threads.h"
23 #include "libmesh/simple_range.h"
24 
25 // C/C++ includes
26 #include <vector>
27 
28 
29 // --------------------------------------------------------
30 // Local anonymous namespace to hold miscellaneous bits
31 namespace
32 {
33 using namespace libMesh;
34 
35 // Mutex object for required locking
36 typedef Threads::spin_mutex SingletonMutex;
37 SingletonMutex singleton_mtx, setup_mtx;
38 
39 // global list of runtime Singleton objects - created dynamically,
40 // cleaned up in reverse order.
41 typedef std::vector<Singleton *> SingletonList;
42 
43 SingletonList & get_singleton_cache()
44 {
45  static SingletonList singleton_cache;
46  return singleton_cache;
47 }
48 
49 typedef std::vector<Singleton::Setup *> SetupList;
50 SetupList & get_setup_cache()
51 {
52  static SetupList setup_cache;
53  return setup_cache;
54 }
55 
56 } // end anonymous namespace
57 
58 
59 
60 // --------------------------------------------------------
61 // Local anonymous namespace to hold miscellaneous bits
62 namespace libMesh
63 {
64 
66 {
67  SingletonMutex::scoped_lock lock(singleton_mtx);
68 
69  get_singleton_cache().push_back (this);
70 }
71 
72 
73 
75 {
76  get_setup_cache().push_back (this);
77 }
78 
79 
80 
82 {
83  SingletonMutex::scoped_lock lock(setup_mtx);
84 
85  SetupList & setup_cache = get_setup_cache();
86 
87  for (auto & item : setup_cache)
88  {
89  libmesh_assert (item);
90  item->setup();
91  }
92 }
93 
94 
95 
97 {
98  SingletonMutex::scoped_lock lock(singleton_mtx);
99 
100  SingletonList & singleton_cache = get_singleton_cache();
101 
102  for (auto & item : as_range(singleton_cache.rbegin(),
103  singleton_cache.rend()))
104  {
105  libmesh_assert (item);
106  delete item;
107  item = nullptr;
108  }
109 
110  singleton_cache.clear();
111 }
112 
113 
114 
115 } // namespace libMesh
SimpleRange< I > as_range(const std::pair< I, I > &p)
Definition: simple_range.h:57
static void cleanup()