4 * Copyright (C) 2008 Adam Williams <broadcast at earthling dot net>
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 2 of the License, or
9 * (at your option) any later version.
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License
17 * along with this program; if not, write to the Free Software
18 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
23 #include "bcsignals.h"
25 #include "condition.h"
33 Condition::Condition(int init_value, const char *title, int is_binary)
35 this->is_binary = is_binary;
37 pthread_mutex_init(&mutex, 0);
38 pthread_cond_init(&cond, NULL);
39 this->value = this->init_value = init_value;
42 Condition:: ~Condition()
44 pthread_cond_destroy(&cond);
45 pthread_mutex_destroy(&mutex);
47 UNSET_ALL_LOCKS(this);
51 void Condition::reset()
53 pthread_cond_destroy(&cond);
54 pthread_mutex_destroy(&mutex);
55 pthread_mutex_init(&mutex, 0);
56 pthread_cond_init(&cond, NULL);
60 void Condition::lock(const char *location)
63 SET_LOCK(this, title, location);
65 pthread_mutex_lock(&mutex);
66 while(value <= 0) pthread_cond_wait(&cond, &mutex);
74 pthread_mutex_unlock(&mutex);
77 void Condition::unlock()
79 // The lock trace is created and removed by the acquirer
83 pthread_mutex_lock(&mutex);
88 pthread_cond_signal(&cond);
89 pthread_mutex_unlock(&mutex);
92 int Condition::timed_lock(int microseconds, const char *location)
97 SET_LOCK(this, title, location);
99 pthread_mutex_lock(&mutex);
102 gettimeofday(&now, 0);
104 struct timespec timeout;
105 timeout.tv_sec = now.tv_sec + microseconds / 1000000;
106 timeout.tv_nsec = now.tv_usec * 1000 + (microseconds % 1000000) * 1000;
107 while(value <= 0 && result != ETIMEDOUT)
109 result = pthread_cond_timedwait(&cond, &mutex, &timeout);
113 result = result == ETIMEDOUT ? 1 : -1;
116 struct timeval timeout;
117 int64_t timeout_msec = ((int64_t)microseconds / 1000);
118 // This is based on the most common frame rate since it's mainly used in
120 while( value <= 0 && !result ) {
121 pthread_mutex_unlock(&mutex);
123 gettimeofday(&timeout, 0);
124 timeout.tv_usec -= now.tv_usec;
125 timeout.tv_sec -= now.tv_sec;
126 pthread_mutex_lock(&mutex);
127 if( value > 0 ) break;
128 if( (int64_t)timeout.tv_sec * 1000 +
129 (int64_t)timeout.tv_usec / 1000 > timeout_msec )
137 //printf("Condition::timed_lock 2 %d %s %s\n", result, title, location);
144 pthread_mutex_unlock(&mutex);
149 int Condition::get_value()