2 * Simple semaphore implementation, P() and V().
4 * Copyright (C) 2011-2013 Simon Ruderich
6 * This program is free software: you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation, either version 3 of the License, or
9 * (at your option) any later version.
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License
17 * along with this program. If not, see <http://www.gnu.org/licenses/>.
27 pthread_mutex_t mutex;
28 pthread_cond_t condition;
32 SEM *sem_init(int init_value) {
33 SEM *sem = malloc(sizeof(*sem));
38 if (pthread_mutex_init(&sem->mutex, NULL) != 0) {
42 if (pthread_cond_init(&sem->condition, NULL) != 0) {
43 pthread_mutex_destroy(&sem->mutex);
48 sem->value = init_value;
52 int sem_del(SEM *sem) {
57 if (pthread_mutex_destroy(&sem->mutex) != 0) {
61 if (pthread_cond_destroy(&sem->condition) != 0) {
71 pthread_mutex_lock(&sem->mutex);
72 while (sem->value == 0) {
73 pthread_cond_wait(&sem->condition, &sem->mutex);
76 pthread_mutex_unlock(&sem->mutex);
80 pthread_mutex_lock(&sem->mutex);
82 pthread_cond_broadcast(&sem->condition);
83 pthread_mutex_unlock(&sem->mutex);