Processor Counter Monitor
mutex.h
1 #ifndef MUTEX_HEADER_
2 #define MUTEX_HEADER_
3 
4 #ifdef _MSC_VER
5 #include <windows.h>
6 #else
7 #include <pthread.h>
8 #endif
9 
10 #include <stdlib.h>
11 
12 namespace pcm
13 {
14  class Mutex {
15 #ifdef _MSC_VER
16  HANDLE mutex_;
17 #else
18  pthread_mutex_t mutex_;
19 #endif
20 
21  public:
22  Mutex()
23  {
24 #ifdef _MSC_VER
25  mutex_ = CreateMutex(NULL, FALSE, NULL);
26 #else
27  pthread_mutex_init(&mutex_, NULL);
28 #endif
29  }
30  virtual ~Mutex()
31  {
32 #ifdef _MSC_VER
33  CloseHandle(mutex_);
34 #else
35  if (pthread_mutex_destroy(&mutex_) != 0) std::cerr << "pthread_mutex_destroy failed\n";
36 #endif
37  }
38 
39  void lock()
40  {
41 #ifdef _MSC_VER
42  WaitForSingleObject(mutex_, INFINITE);
43 #else
44  if (pthread_mutex_lock(&mutex_) != 0) std::cerr << "pthread_mutex_lock failed\n";;
45 #endif
46  }
47  void unlock()
48  {
49 #ifdef _MSC_VER
50  ReleaseMutex(mutex_);
51 #else
52  if(pthread_mutex_unlock(&mutex_) != 0) std::cerr << "pthread_mutex_unlock failed\n";
53 #endif
54  }
55 
56  class Scope {
57  Mutex & m;
58  public:
59  Scope(Mutex & m_) : m(m_)
60  {
61  m.lock();
62  }
63  ~Scope() {
64  m.unlock();
65  }
66  };
67  };
68 }
69 
70 #endif
Definition: mutex.h:14
Definition: bw.cpp:12
Definition: mutex.h:56