Stxxl  1.3.2
mutex.h
1 /***************************************************************************
2  * include/stxxl/bits/common/mutex.h
3  *
4  * Part of the STXXL. See http://stxxl.sourceforge.net
5  *
6  * Copyright (C) 2002 Roman Dementiev <[email protected]>
7  * Copyright (C) 2008 Andreas Beckmann <[email protected]>
8  *
9  * Distributed under the Boost Software License, Version 1.0.
10  * (See accompanying file LICENSE_1_0.txt or copy at
11  * http://www.boost.org/LICENSE_1_0.txt)
12  **************************************************************************/
13 
14 #ifndef STXXL_MUTEX_HEADER
15 #define STXXL_MUTEX_HEADER
16 
17 #include <stxxl/bits/namespace.h>
18 
19 #ifdef STXXL_BOOST_THREADS
20 
21  #include <boost/thread/mutex.hpp>
22 
23 #else
24 
25  #include <pthread.h>
26  #include <cerrno>
27 
28  #include <stxxl/bits/noncopyable.h>
29  #include <stxxl/bits/common/error_handling.h>
30 
31 #endif
32 
33 
34 __STXXL_BEGIN_NAMESPACE
35 
36 #ifdef STXXL_BOOST_THREADS
37 
38 typedef boost::mutex mutex;
39 
40 #else
41 
42 class mutex : private noncopyable
43 {
44  pthread_mutex_t _mutex;
45 
46 public:
47  mutex()
48  {
49  check_pthread_call(pthread_mutex_init(&_mutex, NULL));
50  }
51 
52  ~mutex()
53  {
54  int res = pthread_mutex_trylock(&_mutex);
55 
56  if (res == 0 || res == EBUSY) {
57  check_pthread_call(pthread_mutex_unlock(&_mutex));
58  } else
59  stxxl_function_error(resource_error);
60 
61  check_pthread_call(pthread_mutex_destroy(&_mutex));
62  }
63  void lock()
64  {
65  check_pthread_call(pthread_mutex_lock(&_mutex));
66  }
67  void unlock()
68  {
69  check_pthread_call(pthread_mutex_unlock(&_mutex));
70  }
71 };
72 
73 #endif
74 
75 #ifdef STXXL_BOOST_THREADS
76 
77 typedef boost::mutex::scoped_lock scoped_mutex_lock;
78 
79 #else
80 
82 class scoped_mutex_lock
83 {
84  mutex & mtx;
85  bool is_locked;
86 
87 public:
88  scoped_mutex_lock(mutex & mtx_) : mtx(mtx_), is_locked(false)
89  {
90  lock();
91  }
92 
93  ~scoped_mutex_lock()
94  {
95  unlock();
96  }
97 
98  void lock()
99  {
100  if (!is_locked) {
101  mtx.lock();
102  is_locked = true;
103  }
104  }
105 
106  void unlock()
107  {
108  if (is_locked) {
109  mtx.unlock();
110  is_locked = false;
111  }
112  }
113 };
114 
115 #endif
116 
117 __STXXL_END_NAMESPACE
118 
119 #endif // !STXXL_MUTEX_HEADER
Aquire a lock that&#39;s valid until the end of scope.
Definition: mutex.h:82