|
| 1 | + |
| 2 | +#include <glib.h> |
| 3 | +#include "countdown_latch.h" |
| 4 | + |
| 5 | +struct _countdown_latch { |
| 6 | + guint initial_count; |
| 7 | + volatile guint count; |
| 8 | + GCond waiters; |
| 9 | + GMutex lock; |
| 10 | +}; |
| 11 | + |
| 12 | +countdown_latch* countdown_latch_new(guint count) { |
| 13 | + countdown_latch* latch = g_new0(countdown_latch, 1); |
| 14 | + latch->initial_count = count; |
| 15 | + latch->count = count; |
| 16 | + g_mutex_init(&(latch->lock)); |
| 17 | + g_cond_init(&(latch->waiters)); |
| 18 | + return latch; |
| 19 | +} |
| 20 | + |
| 21 | +void countdownlatch_free(countdown_latch* latch) { |
| 22 | + g_cond_clear(&(latch->waiters)); |
| 23 | + g_mutex_clear(&(latch->lock)); |
| 24 | + g_free(latch); |
| 25 | +} |
| 26 | + |
| 27 | +void countdownlatch_wait(countdown_latch* latch) { |
| 28 | + g_mutex_lock(&(latch->lock)); |
| 29 | + while(latch->count > 0) { |
| 30 | + g_cond_wait(&(latch->waiters), &(latch->lock)); |
| 31 | + } |
| 32 | + g_mutex_unlock(&(latch->lock)); |
| 33 | +} |
| 34 | + |
| 35 | +void countdownlatch_count_down(countdown_latch* latch) { |
| 36 | + g_mutex_lock(&(latch->lock)); |
| 37 | + (latch->count)--; |
| 38 | + if(latch->count == 0) { |
| 39 | + g_cond_broadcast(&(latch->waiters)); |
| 40 | + } |
| 41 | + g_mutex_unlock(&(latch->lock)); |
| 42 | +} |
| 43 | + |
| 44 | +void countdownlatch_count_down_wait(countdown_latch* latch) { |
| 45 | + g_mutex_lock(&(latch->lock)); |
| 46 | + (latch->count)--; |
| 47 | + if(latch->count == 0) { |
| 48 | + g_cond_broadcast(&(latch->waiters)); |
| 49 | + } else { |
| 50 | + g_cond_wait(&(latch->waiters), &(latch->lock)); |
| 51 | + } |
| 52 | + g_mutex_unlock(&(latch->lock)); |
| 53 | +} |
| 54 | + |
0 commit comments