00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013 #ifndef STXXL_STATE_HEADER
00014 #define STXXL_STATE_HEADER
00015
00016 #ifdef STXXL_BOOST_THREADS
00017 #include <boost/thread/mutex.hpp>
00018 #include <boost/thread/condition.hpp>
00019 #else
00020 #include <pthread.h>
00021 #endif
00022
00023 #include <stxxl/bits/noncopyable.h>
00024 #include <stxxl/bits/common/utils.h>
00025
00026
00027 __STXXL_BEGIN_NAMESPACE
00028
00029 class state : private noncopyable
00030 {
00031 #ifdef STXXL_BOOST_THREADS
00032 boost::mutex mutex;
00033 boost::condition cond;
00034 #else
00035 pthread_mutex_t mutex;
00036 pthread_cond_t cond;
00037 #endif
00038 int _state;
00039
00040 public:
00041 state(int s = 0) : _state(s)
00042 {
00043 #ifndef STXXL_BOOST_THREADS
00044 check_pthread_call(pthread_mutex_init(&mutex, NULL));
00045 check_pthread_call(pthread_cond_init(&cond, NULL));
00046 #endif
00047 }
00048 ~state()
00049 {
00050 #ifndef STXXL_BOOST_THREADS
00051 int res = pthread_mutex_trylock(&mutex);
00052
00053 if (res == 0 || res == EBUSY) {
00054 check_pthread_call(pthread_mutex_unlock(&mutex));
00055 } else
00056 stxxl_function_error(resource_error);
00057 check_pthread_call(pthread_mutex_destroy(&mutex));
00058 check_pthread_call(pthread_cond_destroy(&cond));
00059 #endif
00060 }
00061 void set_to(int new_state)
00062 {
00063 #ifdef STXXL_BOOST_THREADS
00064 boost::mutex::scoped_lock Lock(mutex);
00065 _state = new_state;
00066 Lock.unlock();
00067 cond.notify_all();
00068 #else
00069 check_pthread_call(pthread_mutex_lock(&mutex));
00070 _state = new_state;
00071 check_pthread_call(pthread_mutex_unlock(&mutex));
00072 check_pthread_call(pthread_cond_broadcast(&cond));
00073 #endif
00074 }
00075 void wait_for(int needed_state)
00076 {
00077 #ifdef STXXL_BOOST_THREADS
00078 boost::mutex::scoped_lock Lock(mutex);
00079 while (needed_state != _state)
00080 cond.wait(Lock);
00081
00082 #else
00083 check_pthread_call(pthread_mutex_lock(&mutex));
00084 while (needed_state != _state)
00085 check_pthread_call(pthread_cond_wait(&cond, &mutex));
00086
00087 check_pthread_call(pthread_mutex_unlock(&mutex));
00088 #endif
00089 }
00090 int operator () ()
00091 {
00092 #ifdef STXXL_BOOST_THREADS
00093 boost::mutex::scoped_lock Lock(mutex);
00094 return _state;
00095 #else
00096 int res;
00097 check_pthread_call(pthread_mutex_lock(&mutex));
00098 res = _state;
00099 check_pthread_call(pthread_mutex_unlock(&mutex));
00100 return res;
00101 #endif
00102 }
00103 };
00104
00105 __STXXL_END_NAMESPACE
00106
00107 #endif // !STXXL_STATE_HEADER