SUNphi  1.0
Mutex.hpp
1 #ifndef _MUTEX_HPP
2 #define _MUTEX_HPP
3 
4 /// \file Barrier.hpp
5 ///
6 /// \brief Define the threads barrier
7 
8 #ifdef HAVE_CONFIG_H
9  #include "config.hpp"
10 #endif
11 
12 #include <cstring>
13 
14 #include <debug/MinimalCrash.hpp>
15 #include <threads/Thread.hpp>
16 
17 namespace SUNphi
18 {
19 #ifdef USE_THREADS
20 
21  /// Class to lock a mutex for the object scope
22  class Mutex
23  {
24  /// Internal mutex
25  pthread_mutex_t mutex PTHREAD_MUTEX_INITIALIZER;
26 
27  public:
28 
29  /// Lock the mutex
30  void lock()
31  {
32  if(pthread_mutex_lock(&mutex))
33  MINIMAL_CRASH("Error locking, %s",strerror(errno));
34  }
35 
36  /// Unlock the mutex
37  void unlock()
38  {
39  if(pthread_mutex_unlock(&mutex))
40  MINIMAL_CRASH("Error unlocking, %s",strerror(errno));
41  }
42  };
43 
44  /// Keep a mutex locked for the duration of the object
45  class ScopeMutexLocker
46  {
47  /// Reference to the mutex
48  Mutex& mutex;
49 
50  public:
51 
52  /// Create, store the reference and lock
53  ScopeMutexLocker(Mutex& mutex) ///< Mutex to be kept locked
54  : mutex(mutex)
55  {
56  mutex.lock();
57  }
58 
59  /// Unlock and destroy
60  ~ScopeMutexLocker()
61  {
62  mutex.unlock();
63  }
64  };
65 
66 #else
67 
68  /// Dummy mutex
69  struct Mutex
70  {
71  /// Lock the mutex
72  void lock()
73  {
74  }
75 
76  /// Unlock the mutex
77  void unlock()
78  {
79  }
80  };
81 
82  /// Dummy set a scope mutex locker
83 #define THREADS_SCOPE_SEQUENTIAL()
84 
85  /// Dummy scope mutex locker
86  struct ScopeMutexLocker
87  {
88  };
89 
90 #endif
91 }
92 
93 #endif
#define MINIMAL_CRASH(...)
Initialize the minimal crasher.
void minimalCrash(const char *path, const int line, const char *funcName, const char *format,...)
Definition: SUNphi.cpp:53