r125: This commit was manufactured by cvs2svn to create tag 'r1_1_7-last'.
[cinelerra_cv/mob.git] / hvirtual / guicast / condition.C
blobc1a9664e850e7bf90082381da4626bf5dc267efb
1 #include "condition.h"
3 #include <errno.h>
4 #include <sys/time.h>
6 Condition::Condition(int init_value)
8         pthread_mutex_init(&mutex, 0);
9         pthread_cond_init(&cond, NULL);
10         value = init_value;
13 Condition:: ~Condition()
15     pthread_cond_destroy(&cond);
16     pthread_mutex_destroy(&mutex);
20 void Condition::lock()
22     pthread_mutex_lock(&mutex);
23     while(value <= 0) pthread_cond_wait(&cond, &mutex);
24         value--;
25     pthread_mutex_unlock(&mutex);
28 void Condition::unlock()
30     pthread_mutex_lock(&mutex);
31     value++;
32     pthread_cond_signal(&cond);
33     pthread_mutex_unlock(&mutex);
36 int Condition::timed_lock(int milliseconds)
38     struct timeval now;
39     struct timespec timeout;
40     int result = 0;
42     pthread_mutex_lock(&mutex);
43     gettimeofday(&now, 0);
44     timeout.tv_sec = now.tv_sec + milliseconds / 1000000;
45     timeout.tv_nsec = now.tv_usec * 1000 + (milliseconds % 1000000) * 1000;
47     while(value <= 0 && result != ETIMEDOUT)
48         {
49                 result = pthread_cond_timedwait(&cond, &mutex, &timeout);
50     }
52     if(result == ETIMEDOUT) 
53         {
54                 result = 1;
55     } 
56         else 
57         {
58                 value--;
59                 result = 0;
60     }
61     pthread_mutex_unlock(&mutex);
62         return result;