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
|
/* wg.c - Thread management tools modeled on
* https://golang.org/pkg/sync/#WaitGroup
*
* Copyright (C) 2016 Luke Shumaker
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <errno.h>
#include <error.h>
#include <stdlib.h> /* for EXIT_FAILURE */
#include <unistd.h>
#include "wg.h"
/* pthread_cond_t is overly complicated. Just use a self-pipe. */
void wg_init(struct wg *wg) {
wg->count = 0;
pthread_mutex_init(&wg->lock, NULL);
int fds[2];
if (pipe(fds) != 0)
error(EXIT_FAILURE, errno, "pipe");
wg->fd_wait = fds[0];
wg->fd_signal = fds[1];
}
void wg_add(struct wg *wg, unsigned int n) {
pthread_mutex_lock(&wg->lock);
wg->count += n;
pthread_mutex_unlock(&wg->lock);
}
void wg_sub(struct wg *wg, unsigned int n) {
pthread_mutex_lock(&wg->lock);
wg->count -= n;
if (wg->count == 0)
if (write(wg->fd_signal, " ", 1) < 1)
error(EXIT_FAILURE, errno, "write");
pthread_mutex_unlock(&wg->lock);
}
void wg_wait(struct wg *wg) {
char b;
retry:
if (read(wg->fd_wait, &b, 1) == -1) {
if (errno == EINTR)
goto retry;
error(EXIT_FAILURE, errno, "wg_wait");
}
}
|