Stxxl  1.2.1
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 <dementiev@mpi-sb.mpg.de>
7  * Copyright (C) 2008 Andreas Beckmann <beckmann@cs.uni-frankfurt.de>
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 
27  #include <stxxl/bits/noncopyable.h>
28  #include <stxxl/bits/common/utils.h>
29 
30 #endif
31 
32 
33 __STXXL_BEGIN_NAMESPACE
34 
35 #ifdef STXXL_BOOST_THREADS
36 
37 typedef boost::mutex mutex;
38 
39 #else
40 
41 class mutex : private noncopyable
42 {
43  pthread_mutex_t _mutex;
44 
45 public:
46  mutex()
47  {
48  check_pthread_call(pthread_mutex_init(&_mutex, NULL));
49  }
50 
51  ~mutex()
52  {
53  int res = pthread_mutex_trylock(&_mutex);
54 
55  if (res == 0 || res == EBUSY) {
56  check_pthread_call(pthread_mutex_unlock(&_mutex));
57  } else
58  stxxl_function_error(resource_error);
59 
60  check_pthread_call(pthread_mutex_destroy(&_mutex));
61  }
62  void lock()
63  {
64  check_pthread_call(pthread_mutex_lock(&_mutex));
65  }
66  void unlock()
67  {
68  check_pthread_call(pthread_mutex_unlock(&_mutex));
69  }
70 };
71 
72 #endif
73 
74 #ifdef STXXL_BOOST_THREADS
75 
76 typedef boost::mutex::scoped_lock scoped_mutex_lock;
77 
78 #else
79 
81 class scoped_mutex_lock
82 {
83  mutex & mtx;
84  bool is_locked;
85 
86 public:
87  scoped_mutex_lock(mutex & mtx_) : mtx(mtx_), is_locked(false)
88  {
89  lock();
90  }
91 
92  ~scoped_mutex_lock()
93  {
94  unlock();
95  }
96 
97  void lock()
98  {
99  if (!is_locked) {
100  mtx.lock();
101  is_locked = true;
102  }
103  }
104 
105  void unlock()
106  {
107  if (is_locked) {
108  mtx.unlock();
109  is_locked = false;
110  }
111  }
112 };
113 
114 #endif
115 
116 __STXXL_END_NAMESPACE
117 
118 #endif // !STXXL_MUTEX_HEADER