/* 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 . */ #include #include #include /* for EXIT_FAILURE */ #include #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"); } }