-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfutex_latch.c
More file actions
108 lines (99 loc) · 2.26 KB
/
Copy pathfutex_latch.c
File metadata and controls
108 lines (99 loc) · 2.26 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
#define _GNU_SOURCE
#define _POSIX_C_SOURCE 200809L
#include <stdatomic.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <errno.h>
#include <time.h>
#include <unistd.h>
#include <limits.h>
#if defined(__linux__)
#include <sys/syscall.h>
#include <linux/futex.h>
#include <sys/time.h>
static int futex_wait(atomic_int *addr, int expected)
{
return syscall(SYS_futex, (int *)addr, FUTEX_WAIT, expected, NULL, NULL, 0);
}
static int futex_wake(atomic_int *addr)
{
return syscall(SYS_futex, (int *)addr, FUTEX_WAKE, INT_MAX, NULL, NULL, 0);
}
#endif
typedef struct {
atomic_int state;
#if !defined(__linux__)
pthread_mutex_t m;
pthread_cond_t c;
#endif
} latch_t;
static void latch_init(latch_t *l)
{
atomic_init(&l->state, 0);
#if !defined(__linux__)
pthread_mutex_init(&l->m, NULL);
pthread_cond_init(&l->c, NULL);
#endif
}
static void latch_release(latch_t *l)
{
int prev = atomic_exchange_explicit(&l->state, 1, memory_order_release);
#if defined(__linux__)
if (prev == 0) futex_wake(&l->state);
#else
if (prev == 0) {
pthread_mutex_lock(&l->m);
pthread_cond_broadcast(&l->c);
pthread_mutex_unlock(&l->m);
}
#endif
}
static void latch_wait(latch_t *l)
{
for (;;) {
int s = atomic_load_explicit(&l->state, memory_order_acquire);
if (s == 1) return;
#if defined(__linux__)
futex_wait(&l->state, 0);
#else
pthread_mutex_lock(&l->m);
while (atomic_load_explicit(&l->state, memory_order_acquire) == 0) {
pthread_cond_wait(&l->c, &l->m);
}
pthread_mutex_unlock(&l->m);
#endif
}
}
typedef struct {
latch_t *l;
int id;
} arg_t;
static void *worker(void *p)
{
arg_t *a = p;
latch_wait(a->l);
printf("worker %d passed latch\n", a->id);
return NULL;
}
int main(void)
{
latch_t l;
latch_init(&l);
pthread_t th[4];
arg_t a[4];
for (int i = 0; i < 4; i++) {
a[i].l = &l;
a[i].id = i;
pthread_create(&th[i], NULL, worker, &a[i]);
}
struct timespec ts = { .tv_sec = 1, .tv_nsec = 0 };
nanosleep(&ts, NULL);
printf("releasing latch\n");
latch_release(&l);
for (int i = 0; i < 4; i++) {
pthread_join(th[i], NULL);
}
return 0;
}