Galois
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Pages
StaticInstance.h
Go to the documentation of this file.
1 /*
2  * This file belongs to the Galois project, a C++ library for exploiting
3  * parallelism. The code is being released under the terms of the 3-Clause BSD
4  * License (a copy is located in LICENSE.txt at the top-level directory).
5  *
6  * Copyright (C) 2018, The University of Texas at Austin. All rights reserved.
7  * UNIVERSITY EXPRESSLY DISCLAIMS ANY AND ALL WARRANTIES CONCERNING THIS
8  * SOFTWARE AND DOCUMENTATION, INCLUDING ANY WARRANTIES OF MERCHANTABILITY,
9  * FITNESS FOR ANY PARTICULAR PURPOSE, NON-INFRINGEMENT AND WARRANTIES OF
10  * PERFORMANCE, AND ANY WARRANTY THAT MIGHT OTHERWISE ARISE FROM COURSE OF
11  * DEALING OR USAGE OF TRADE. NO WARRANTY IS EITHER EXPRESS OR IMPLIED WITH
12  * RESPECT TO THE USE OF THE SOFTWARE OR DOCUMENTATION. Under no circumstances
13  * shall University be liable for incidental, special, indirect, direct or
14  * consequential damages or loss of profits, interruption of business, or
15  * related expenses which may arise from use of Software or Documentation,
16  * including but not limited to those resulting from defects in Software and/or
17  * Documentation, or loss or inaccuracy of data of any kind.
18  */
19 
20 #ifndef GALOIS_SUBSTRATE_STATICINSTANCE_H
21 #define GALOIS_SUBSTRATE_STATICINSTANCE_H
22 
23 #include "galois/config.h"
25 
26 namespace galois {
27 namespace substrate {
28 
29 // This should be much simpler in c++03 mode, but be general for now
30 // This exists because ptrlock is not a pod, but this is.
31 template <typename T>
33  volatile T* V;
34  volatile int _lock;
35 
36  inline void lock() {
37  int oldval;
38  do {
39  while (_lock != 0) {
40  substrate::asmPause();
41  }
42  oldval = __sync_fetch_and_or(&_lock, 1);
43  } while (oldval & 1);
44  }
45 
46  inline void unlock() {
47  compilerBarrier();
48  _lock = 0;
49  }
50 
51  T* get() {
52  volatile T* val = V;
53  if (val)
54  return (T*)val;
55  lock();
56  val = V;
57  if (!val)
58  V = val = new T();
59  unlock();
60  return (T*)val;
61  }
62 };
63 
64 } // end namespace substrate
65 } // end namespace galois
66 
67 #endif
Definition: StaticInstance.h:32
volatile int _lock
Definition: StaticInstance.h:34
void unlock()
Definition: StaticInstance.h:46
void lock()
Definition: StaticInstance.h:36
volatile T * V
Definition: StaticInstance.h:33