2 * Copyright (c) 2008-2012 Zmanda, Inc. All Rights Reserved.
4 * This program is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU General Public License
6 * as published by the Free Software Foundation; either version 2
7 * of the License, or (at your option) any later version.
9 * This program is distributed in the hope that it will be useful, but
10 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
11 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
14 * You should have received a copy of the GNU General Public License along
15 * with this program; if not, write to the Free Software Foundation, Inc.,
16 * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
18 * Contact information: Zmanda Inc., 465 S. Mathilda Ave., Suite 300
19 * Sunnyvale, CA 94085, USA, or: http://www.zmanda.com
22 /* GLib does not provide semaphores, which are useful in queue.c.
23 So, we implement it here. */
26 #include "amsemaphore.h"
28 amsemaphore_t* amsemaphore_new_with_value(int value) {
31 if (!g_thread_supported())
34 rval = malloc(sizeof(*rval));
36 rval->mutex = g_mutex_new();
37 rval->decrement_cond = g_cond_new();
38 rval->zero_cond = g_cond_new();
40 if (rval->mutex == NULL || rval->decrement_cond == NULL ||
41 rval->zero_cond == NULL) {
42 amsemaphore_free(rval);
49 void amsemaphore_free(amsemaphore_t* o) {
50 g_mutex_free(o->mutex);
51 g_cond_free(o->decrement_cond);
52 g_cond_free(o->zero_cond);
56 /* This function checks if the semaphore would is zero or negative.
57 * If so, the zero_cond is signalled. We assume that the mutex is
59 static void check_empty(amsemaphore_t * o) {
61 g_cond_broadcast(o->zero_cond);
65 void amsemaphore_increment(amsemaphore_t* o, unsigned int inc) {
66 g_return_if_fail(o != NULL);
67 g_return_if_fail(inc != 0);
69 amsemaphore_force_adjust(o, inc);
72 void amsemaphore_decrement(amsemaphore_t* o, unsigned int dec) {
74 g_return_if_fail(o != NULL);
76 g_return_if_fail(sdec >= 0);
78 g_mutex_lock(o->mutex);
79 while (o->value < sdec) {
80 g_cond_wait(o->decrement_cond, o->mutex);
84 g_mutex_unlock(o->mutex);
87 void amsemaphore_force_adjust(amsemaphore_t* o, int inc) {
88 g_return_if_fail(o != NULL);
90 g_mutex_lock(o->mutex);
95 g_cond_broadcast(o->decrement_cond);
96 g_mutex_unlock(o->mutex);
100 void amsemaphore_force_set(amsemaphore_t* o, int value) {
102 g_return_if_fail(o != NULL);
104 g_mutex_lock(o->mutex);
107 if (value < oldvalue)
110 g_cond_broadcast(o->decrement_cond);
111 g_mutex_unlock(o->mutex);
115 void amsemaphore_wait_empty(amsemaphore_t * o) {
116 g_return_if_fail(o != NULL);
118 g_mutex_lock(o->mutex);
119 while (o->value > 0) {
120 g_cond_wait(o->zero_cond, o->mutex);
122 g_mutex_unlock(o->mutex);