Main Page | Class Hierarchy | Alphabetical List | Class List | Directories | File List | Class Members | File Members

condition.C

Go to the documentation of this file.
00001 #include "bcsignals.h"
00002 #include "condition.h"
00003 
00004 #include <errno.h>
00005 #include <stdio.h>
00006 #include <sys/time.h>
00007 
00008 Condition::Condition(int init_value, char *title)
00009 {
00010         this->title = title;
00011         pthread_mutex_init(&mutex, 0);
00012         pthread_cond_init(&cond, NULL);
00013         this->value = this->init_value = init_value;
00014 }
00015 
00016 Condition:: ~Condition()
00017 {
00018     pthread_cond_destroy(&cond);
00019     pthread_mutex_destroy(&mutex);
00020         UNSET_ALL_LOCKS(this);
00021 }
00022 
00023 void Condition::reset()
00024 {
00025     pthread_cond_destroy(&cond);
00026     pthread_mutex_destroy(&mutex);
00027         pthread_mutex_init(&mutex, 0);
00028         pthread_cond_init(&cond, NULL);
00029         value = init_value;
00030 }
00031 
00032 void Condition::lock(char *location)
00033 {
00034         SET_LOCK(this, title, location);
00035     pthread_mutex_lock(&mutex);
00036     while(value <= 0) pthread_cond_wait(&cond, &mutex);
00037         SET_LOCK2
00038         value--;
00039     pthread_mutex_unlock(&mutex);
00040 }
00041 
00042 void Condition::unlock()
00043 {
00044         UNSET_LOCK(this);
00045     pthread_mutex_lock(&mutex);
00046     value++;
00047     pthread_cond_signal(&cond);
00048     pthread_mutex_unlock(&mutex);
00049 }
00050 
00051 int Condition::timed_lock(int microseconds, char *location)
00052 {
00053     struct timeval now;
00054     struct timespec timeout;
00055     int result = 0;
00056 
00057         SET_LOCK(this, title, location);
00058     pthread_mutex_lock(&mutex);
00059     gettimeofday(&now, 0);
00060     timeout.tv_sec = now.tv_sec + microseconds / 1000000;
00061     timeout.tv_nsec = now.tv_usec * 1000 + (microseconds % 1000000) * 1000;
00062 
00063     while(value <= 0 && result != ETIMEDOUT)
00064         {
00065                 result = pthread_cond_timedwait(&cond, &mutex, &timeout);
00066     }
00067 
00068     if(result == ETIMEDOUT) 
00069         {
00070 //printf("Condition::timed_lock 1 %s %s\n", title, location);
00071                 UNSET_LOCK2
00072                 result = 1;
00073     } 
00074         else 
00075         {
00076 //printf("Condition::timed_lock 2 %s %s\n", title, location);
00077                 SET_LOCK2
00078                 value--;
00079                 result = 0;
00080     }
00081     pthread_mutex_unlock(&mutex);
00082         return result;
00083 }
00084 
00085 
00086 int Condition::get_value()
00087 {
00088         return value;
00089 }

Generated on Sun Jan 8 13:26:34 2006 for Guicast-svn by  doxygen 1.4.4