So-Bogus
A c++ sparse block matrix library aimed at Second Order cone problems
 All Classes Namespaces Functions Variables Typedefs Enumerations Enumerator Pages
Lock.hpp
1 /*
2  * This file is part of bogus, a C++ sparse block matrix library.
3  *
4  * Copyright 2013 Gilles Daviet <gdaviet@gmail.com>
5  *
6  * This Source Code Form is subject to the terms of the Mozilla Public
7  * License, v. 2.0. If a copy of the MPL was not distributed with this
8  * file, You can obtain one at http://mozilla.org/MPL/2.0/.
9 */
10 
11 #ifndef BOGUS_LOCK_HPP
12 #define BOGUS_LOCK_HPP
13 
14 #ifdef _OPENMP
15 #include <omp.h>
16 #endif
17 
18 namespace bogus {
19 
20 namespace lock_impl {
21 
22 #ifdef _OPENMP
23 typedef omp_lock_t RawData ;
24 #else
25 typedef void* RawData ;
26 #endif
27 
29 {
30  mutable union {
31  RawData api_type ;
32  unsigned char padding[24] ;
33  } data;
34 
35  void (*set_f )(RawData*) ;
36  void (*unset_f)(RawData*) ;
37 
38  void set() const {
39  if( set_f ) set_f( &data.api_type ) ;
40  }
41 
42  void unset() const {
43  if( unset_f ) unset_f( &data.api_type ) ;
44  }
45 
46 } ;
47 
48 } //namespace lock_impl
49 
50 #ifndef _OPENMP
51 class Lock {
52 public:
53  lock_impl::AbstractLock for_abi_compat ;
54 
55  Lock()
56  {
57  for_abi_compat. set_f = 0 ;
58  for_abi_compat.unset_f = 0 ;
59  }
60 
61  template< bool DoLock = true >
62  struct Guard {
63  explicit Guard( Lock& ) {}
64  ~Guard() {}
65  } ;
66 };
67 #else
68 
69 class Lock {
70 
71 public:
72  template< bool DoLock = true >
73  struct Guard {
74  explicit Guard( const Lock& lock )
75  : m_lock( lock )
76  {
77  if(DoLock) m_lock.set() ;
78  }
79 
80  ~Guard()
81  {
82  if(DoLock) m_lock.unset() ;
83  }
84 
85  private:
86  Guard(const Guard &guard) ;
87  Guard& operator=(const Guard &guard) ;
88 
89  const Lock &m_lock ;
90  } ;
91 
92  Lock()
93  {
94  init() ;
95  }
96 
97  Lock( const Lock& )
98  {
99  init() ;
100  }
101 
102  Lock& operator=( const Lock& )
103  {
104  return *this ;
105  }
106 
107  ~Lock()
108  {
109  omp_destroy_lock( data() ) ;
110  }
111 
112  void set() const {
113  m_impl.set() ;
114  }
115 
116  void unset() const {
117  m_impl.unset() ;
118  }
119 
120  lock_impl::RawData* data() const {
121  return &m_impl.data.api_type ;
122  }
123 
124 private:
125 
126  void init()
127  {
128  m_impl. set_f = &omp_set_lock ;
129  m_impl.unset_f = &omp_unset_lock ;
130  omp_init_lock( data() ) ;
131  }
132 
133  lock_impl::AbstractLock m_impl ;
134 };
135 
136 #endif
137 
138 } //namespace bogus
139 
140 #endif
Definition: Lock.hpp:28
Definition: Lock.hpp:51
Definition: Lock.hpp:62