2 * Simple semaphore implementation, P() and V().
4 * Copyright (C) 2011 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 = (SEM *)malloc(sizeof(SEM));
38 if (0 != pthread_mutex_init(&sem->mutex, NULL)) {
42 if (0 != pthread_cond_init(&sem->condition, NULL)) {
43 pthread_mutex_destroy(&sem->mutex);
48 sem->value = init_value;
52 int sem_del(SEM *sem) {
57 if (0 != pthread_mutex_destroy(&sem->mutex)) {
61 if (0 != pthread_cond_destroy(&sem->condition)) {
71 pthread_mutex_lock(&sem->mutex);
72 while (0 == sem->value) {
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);