]> ruderich.org/simon Gitweb - tlsproxy/tlsproxy.git/blob - src/sem.c
Disable RC4.
[tlsproxy/tlsproxy.git] / src / sem.c
1 /*
2  * Simple semaphore implementation, P() and V().
3  *
4  * Copyright (C) 2011-2014  Simon Ruderich
5  *
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.
10  *
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.
15  *
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/>.
18  */
19
20 #include "sem.h"
21
22 #include <pthread.h>
23 #include <stdlib.h>
24
25
26 struct SEM {
27     pthread_mutex_t mutex;
28     pthread_cond_t  condition;
29     int value;
30 };
31
32 SEM *sem_init(int init_value) {
33     SEM *sem = malloc(sizeof(*sem));
34     if (sem == NULL) {
35         return NULL;
36     }
37
38     if (pthread_mutex_init(&sem->mutex, NULL) != 0) {
39         free(sem);
40         return NULL;
41     }
42     if (pthread_cond_init(&sem->condition, NULL) != 0) {
43         pthread_mutex_destroy(&sem->mutex);
44         free(sem);
45         return NULL;
46     }
47
48     sem->value = init_value;
49     return sem;
50 }
51
52 int sem_del(SEM *sem) {
53     if (sem == NULL) {
54         return 0;
55     }
56
57     if (pthread_mutex_destroy(&sem->mutex) != 0) {
58         free(sem);
59         return -1;
60     }
61     if (pthread_cond_destroy(&sem->condition) != 0) {
62         free(sem);
63         return -1;
64     }
65
66     free(sem);
67     return 0;
68 }
69
70 void P(SEM *sem) {
71     pthread_mutex_lock(&sem->mutex);
72     while (sem->value <= 0) {
73         pthread_cond_wait(&sem->condition, &sem->mutex);
74     }
75     sem->value--;
76     pthread_mutex_unlock(&sem->mutex);
77 }
78
79 void V(SEM *sem) {
80     pthread_mutex_lock(&sem->mutex);
81     sem->value++;
82     pthread_cond_broadcast(&sem->condition);
83     pthread_mutex_unlock(&sem->mutex);
84 }