X-Git-Url: https://ruderich.org/simon/gitweb/?a=blobdiff_plain;f=src%2Fsem.c;fp=src%2Fsem.c;h=86fe39882c54a315e04a2f0b773f0b08db4aa801;hb=b5aeb6f8ea2147f64be9a8ce750917aed4bf7cef;hp=0000000000000000000000000000000000000000;hpb=5a1ebfbc563350d4492f143f96bb1e116b83e881;p=tlsproxy%2Ftlsproxy.git diff --git a/src/sem.c b/src/sem.c new file mode 100644 index 0000000..86fe398 --- /dev/null +++ b/src/sem.c @@ -0,0 +1,84 @@ +/* + * Simple semaphore implementation, P() and V(). + * + * Copyright (C) 2011 Simon Ruderich + * + * 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 "sem.h" + + +struct SEM { + pthread_mutex_t mutex; + pthread_cond_t condition; + int value; +}; + +SEM *sem_init(int init_value) { + SEM *sem = (SEM *)malloc(sizeof(SEM)); + if (NULL == sem) { + return NULL; + } + + if (0 != pthread_mutex_init(&sem->mutex, NULL)) { + free(sem); + return NULL; + } + if (0 != pthread_cond_init(&sem->condition, NULL)) { + pthread_mutex_destroy(&sem->mutex); + free(sem); + return NULL; + } + + sem->value = init_value; + return sem; +} + +int sem_del(SEM *sem) { + if (NULL == sem) { + return 0; + } + + if (0 != pthread_mutex_destroy(&sem->mutex)) { + free(sem); + return -1; + } + if (0 != pthread_cond_destroy(&sem->condition)) { + free(sem); + return -1; + } + + free(sem); + return 0; +} + +void P(SEM *sem) { + pthread_mutex_lock(&sem->mutex); + while (0 == sem->value) { + pthread_cond_wait(&sem->condition, &sem->mutex); + } + sem->value--; + pthread_mutex_unlock(&sem->mutex); +} + +void V(SEM *sem) { + pthread_mutex_lock(&sem->mutex); + sem->value++; + pthread_cond_broadcast(&sem->condition); + pthread_mutex_unlock(&sem->mutex); +}