Skip to content

Commit 2a8b72e

Browse files
author
DenverM80
committed
add countdown latch implementation using glib mutexes to use in improving tests
1 parent 536bf24 commit 2a8b72e

File tree

2 files changed

+68
-0
lines changed

2 files changed

+68
-0
lines changed

test/countdown_latch.c

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
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+

test/countdown_latch.h

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
#ifndef COUNTDOWN_LATCH_H_
2+
#define COUNTDOWN_LATCH_H_
3+
4+
typedef struct _countdown_latch countdown_latch;
5+
6+
countdown_latch* countdown_latch_new(guint count);
7+
void countdown_latch_free(countdown_latch* latch);
8+
9+
void countdown_latch_wait(countdown_latch* latch);
10+
void countdown_latch_count_down(countdown_latch* latch);
11+
void countdown_latch_count_down_and_wait(countdown_latch* latch);
12+
13+
#endif /* COUNTDOWN_LATCH_H_ */
14+
#endif

0 commit comments

Comments
 (0)