r134: Heroine Virtual's release 1.1.8
[cinelerra_cv/mob.git] / hvirtual / guicast / condition.C
blob7965fea828ac902b25e4238f9d034fda91f53eb4
1 #include "bcsignals.h"
2 #include "condition.h"
4 #include <errno.h>
5 #include <sys/time.h>
7 Condition::Condition(int init_value, char *title)
9         this->title = title;
10         pthread_mutex_init(&mutex, 0);
11         pthread_cond_init(&cond, NULL);
12         this->value = this->init_value = init_value;
15 Condition:: ~Condition()
17     pthread_cond_destroy(&cond);
18     pthread_mutex_destroy(&mutex);
19         UNSET_ALL_LOCKS(this);
22 void Condition::reset()
24     pthread_cond_destroy(&cond);
25     pthread_mutex_destroy(&mutex);
26         pthread_mutex_init(&mutex, 0);
27         pthread_cond_init(&cond, NULL);
28         value = init_value;
31 void Condition::lock(char *location)
33         SET_LOCK(this, title, location);
34     pthread_mutex_lock(&mutex);
35     while(value <= 0) pthread_cond_wait(&cond, &mutex);
36         value--;
37     pthread_mutex_unlock(&mutex);
40 void Condition::unlock()
42         UNSET_LOCK(this);
43     pthread_mutex_lock(&mutex);
44     value++;
45     pthread_cond_signal(&cond);
46     pthread_mutex_unlock(&mutex);
49 int Condition::timed_lock(int microseconds, char *location)
51     struct timeval now;
52     struct timespec timeout;
53     int result = 0;
55         SET_LOCK(this, title, location);
56     pthread_mutex_lock(&mutex);
57     gettimeofday(&now, 0);
58     timeout.tv_sec = now.tv_sec + microseconds / 1000000;
59     timeout.tv_nsec = now.tv_usec * 1000 + (microseconds % 1000000) * 1000;
61     while(value <= 0 && result != ETIMEDOUT)
62         {
63                 result = pthread_cond_timedwait(&cond, &mutex, &timeout);
64     }
66     if(result == ETIMEDOUT) 
67         {
68                 result = 1;
69     } 
70         else 
71         {
72                 value--;
73                 result = 0;
74     }
75     pthread_mutex_unlock(&mutex);
76         return result;
80 int Condition::get_value()
82         return value;