00001 #ifndef IBRCOMMON_CONDITIONAL_H_
00002 #define IBRCOMMON_CONDITIONAL_H_
00003
00004 #include <stdlib.h>
00005 #include <errno.h>
00006 #include <pthread.h>
00007 #include "ibrcommon/thread/Mutex.h"
00008
00009 namespace ibrcommon
00010 {
00011 class Conditional : public Mutex
00012 {
00013 public:
00014 Conditional();
00015 virtual ~Conditional();
00016
00017 void signal(bool broadcast = false);
00018 void wait();
00019
00020
00021
00022
00023
00024
00025 bool wait(size_t timeout);
00026
00027 bool wait(struct timespec *ts);
00028
00029 protected:
00036 static void gettimeout(size_t timeout, struct timespec *hires);
00037
00038 private:
00039 class attribute
00040 {
00041 public:
00042 pthread_condattr_t attr;
00043 attribute();
00044 };
00045
00046 pthread_cond_t cond;
00047
00048 static attribute attr;
00049 };
00050
00051 template<class T, T block>
00052 class StatefulConditional : public Conditional
00053 {
00054 public:
00055 StatefulConditional(T state) : _state(state) {};
00056 virtual ~StatefulConditional() {};
00057
00058 void setState(T state)
00059 {
00060 if (ifState(block)) return;
00061 _state = state;
00062 this->signal(true);
00063 }
00064
00065 bool waitState(T state)
00066 {
00067 while (!ifState(state))
00068 {
00069 if (ifState(block)) return false;
00070 wait();
00071 }
00072
00073 return true;
00074 }
00075
00076 T getState()
00077 {
00078 return _state;
00079 }
00080
00081 bool ifState(T state)
00082 {
00083 return (state == _state);
00084 }
00085
00086 private:
00087 T _state;
00088 };
00089 }
00090
00091 #endif