+/*
+ * 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 <http://www.gnu.org/licenses/>.
+ */
+
+#include <stdlib.h>
+#include <pthread.h>
+
+#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);
+}