Stxxl  1.2.1
state.h
1 /***************************************************************************
2  * include/stxxl/bits/common/state.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  *
8  * Distributed under the Boost Software License, Version 1.0.
9  * (See accompanying file LICENSE_1_0.txt or copy at
10  * http://www.boost.org/LICENSE_1_0.txt)
11  **************************************************************************/
12 
13 #ifndef STXXL_STATE_HEADER
14 #define STXXL_STATE_HEADER
15 
16 #ifdef STXXL_BOOST_THREADS
17  #include <boost/thread/mutex.hpp>
18  #include <boost/thread/condition.hpp>
19 #else
20  #include <pthread.h>
21 #endif
22 
23 #include <stxxl/bits/noncopyable.h>
24 #include <stxxl/bits/common/utils.h>
25 
26 
27 __STXXL_BEGIN_NAMESPACE
28 
29 class state : private noncopyable
30 {
31 #ifdef STXXL_BOOST_THREADS
32  boost::mutex mutex;
33  boost::condition cond;
34 #else
35  pthread_mutex_t mutex;
36  pthread_cond_t cond;
37 #endif
38  int _state;
39 
40 public:
41  state(int s = 0) : _state(s)
42  {
43 #ifndef STXXL_BOOST_THREADS
44  check_pthread_call(pthread_mutex_init(&mutex, NULL));
45  check_pthread_call(pthread_cond_init(&cond, NULL));
46 #endif
47  }
48  ~state()
49  {
50 #ifndef STXXL_BOOST_THREADS
51  int res = pthread_mutex_trylock(&mutex);
52 
53  if (res == 0 || res == EBUSY) {
54  check_pthread_call(pthread_mutex_unlock(&mutex));
55  } else
56  stxxl_function_error(resource_error);
57  check_pthread_call(pthread_mutex_destroy(&mutex));
58  check_pthread_call(pthread_cond_destroy(&cond));
59 #endif
60  }
61  void set_to(int new_state)
62  {
63 #ifdef STXXL_BOOST_THREADS
64  boost::mutex::scoped_lock Lock(mutex);
65  _state = new_state;
66  Lock.unlock();
67  cond.notify_all();
68 #else
69  check_pthread_call(pthread_mutex_lock(&mutex));
70  _state = new_state;
71  check_pthread_call(pthread_mutex_unlock(&mutex));
72  check_pthread_call(pthread_cond_broadcast(&cond));
73 #endif
74  }
75  void wait_for(int needed_state)
76  {
77 #ifdef STXXL_BOOST_THREADS
78  boost::mutex::scoped_lock Lock(mutex);
79  while (needed_state != _state)
80  cond.wait(Lock);
81 
82 #else
83  check_pthread_call(pthread_mutex_lock(&mutex));
84  while (needed_state != _state)
85  check_pthread_call(pthread_cond_wait(&cond, &mutex));
86 
87  check_pthread_call(pthread_mutex_unlock(&mutex));
88 #endif
89  }
90  int operator () ()
91  {
92 #ifdef STXXL_BOOST_THREADS
93  boost::mutex::scoped_lock Lock(mutex);
94  return _state;
95 #else
96  int res;
97  check_pthread_call(pthread_mutex_lock(&mutex));
98  res = _state;
99  check_pthread_call(pthread_mutex_unlock(&mutex));
100  return res;
101 #endif
102  }
103 };
104 
105 __STXXL_END_NAMESPACE
106 
107 #endif // !STXXL_STATE_HEADER