00001 #ifndef NO_GUICAST
00002 #include "bcsignals.h"
00003 #endif
00004 #include "condition.h"
00005
00006 #include <errno.h>
00007 #include <stdio.h>
00008 #include <sys/time.h>
00009
00010 Condition::Condition(int init_value, char *title, int is_binary)
00011 {
00012 this->is_binary = is_binary;
00013 this->title = title;
00014 pthread_mutex_init(&mutex, 0);
00015 pthread_cond_init(&cond, NULL);
00016 this->value = this->init_value = init_value;
00017 }
00018
00019 Condition:: ~Condition()
00020 {
00021 pthread_cond_destroy(&cond);
00022 pthread_mutex_destroy(&mutex);
00023 #ifndef NO_GUICAST
00024 UNSET_ALL_LOCKS(this);
00025 #endif
00026 }
00027
00028 void Condition::reset()
00029 {
00030 pthread_cond_destroy(&cond);
00031 pthread_mutex_destroy(&mutex);
00032 pthread_mutex_init(&mutex, 0);
00033 pthread_cond_init(&cond, NULL);
00034 value = init_value;
00035 }
00036
00037 void Condition::lock(char *location)
00038 {
00039 #ifndef NO_GUICAST
00040 SET_LOCK(this, title, location);
00041 #endif
00042 pthread_mutex_lock(&mutex);
00043 while(value <= 0) pthread_cond_wait(&cond, &mutex);
00044 #ifndef NO_GUICAST
00045 UNSET_LOCK2
00046 #endif
00047 if(is_binary)
00048 value = 0;
00049 else
00050 value--;
00051 pthread_mutex_unlock(&mutex);
00052 }
00053
00054 void Condition::unlock()
00055 {
00056
00057
00058
00059
00060 pthread_mutex_lock(&mutex);
00061 if(is_binary)
00062 value = 1;
00063 else
00064 value++;
00065 pthread_cond_signal(&cond);
00066 pthread_mutex_unlock(&mutex);
00067 }
00068
00069 int Condition::timed_lock(int microseconds, char *location)
00070 {
00071 struct timeval now;
00072 struct timespec timeout;
00073 int result = 0;
00074
00075 #ifndef NO_GUICAST
00076 SET_LOCK(this, title, location);
00077 #endif
00078 pthread_mutex_lock(&mutex);
00079 gettimeofday(&now, 0);
00080 timeout.tv_sec = now.tv_sec + microseconds / 1000000;
00081 timeout.tv_nsec = now.tv_usec * 1000 + (microseconds % 1000000) * 1000;
00082
00083 while(value <= 0 && result != ETIMEDOUT)
00084 {
00085 result = pthread_cond_timedwait(&cond, &mutex, &timeout);
00086 }
00087
00088 if(result == ETIMEDOUT)
00089 {
00090
00091 #ifndef NO_GUICAST
00092 UNSET_LOCK2
00093 #endif
00094 result = 1;
00095 }
00096 else
00097 {
00098
00099 #ifndef NO_GUICAST
00100 UNSET_LOCK2
00101 #endif
00102 if(is_binary)
00103 value = 0;
00104 else
00105 value--;
00106 result = 0;
00107 }
00108 pthread_mutex_unlock(&mutex);
00109 return result;
00110 }
00111
00112
00113 int Condition::get_value()
00114 {
00115 return value;
00116 }