kinetic-c  v0.12.0
Seagate Kinetic Protocol Client Library for C
kinetic_semaphore.c
Go to the documentation of this file.
1 /*
2 * kinetic-c
3 * Copyright (C) 2015 Seagate Technology.
4 *
5 * This program is free software; you can redistribute it and/or
6 * modify it under the terms of the GNU General Public License
7 * as published by the Free Software Foundation; either version 2
8 * of the License, or (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License
16 * along with this program; if not, write to the Free Software
17 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 *
19 */
20 #include "kinetic_semaphore.h"
21 #include <pthread.h>
22 #include <stdlib.h>
23 
24 struct _KineticSemaphore
25 {
26  pthread_mutex_t mutex;
27  pthread_cond_t complete;
28  bool signaled;
29 };
30 
31 KineticSemaphore * KineticSemaphore_Create(void)
32 {
33  KineticSemaphore * sem = calloc(1, sizeof(KineticSemaphore));
34  if (sem != NULL)
35  {
36  pthread_mutex_init(&sem->mutex, NULL);
37  pthread_cond_init(&sem->complete, NULL);
38  sem->signaled = false;
39  }
40  return sem;
41 }
42 
43 void KineticSemaphore_Signal(KineticSemaphore * sem)
44 {
45  pthread_mutex_lock(&sem->mutex);
46  sem->signaled = true;
47  pthread_cond_signal(&sem->complete);
48  pthread_mutex_unlock(&sem->mutex);
49 }
50 
51 bool KineticSemaphore_CheckSignaled(KineticSemaphore * sem)
52 {
53  return sem->signaled;
54 }
55 
56 bool KineticSemaphore_DestroyIfSignaled(KineticSemaphore * sem)
57 {
58  if (sem->signaled) {
59  pthread_mutex_destroy(&sem->mutex);
60  pthread_cond_destroy(&sem->complete);
61  free(sem);
62  return true;
63  }
64  else {
65  return false; // Semaphore has not yet been signaled
66  }
67 }
68 
69 void KineticSemaphore_WaitForSignalAndDestroy(KineticSemaphore * sem)
70 {
71  pthread_mutex_lock(&sem->mutex);
72  if (!sem->signaled) {
73  pthread_cond_wait(&sem->complete, &sem->mutex);
74  }
75  pthread_mutex_unlock(&sem->mutex);
76 
77  pthread_mutex_destroy(&sem->mutex);
78  pthread_cond_destroy(&sem->complete);
79 
80  free(sem);
81 }
82 
bool KineticSemaphore_DestroyIfSignaled(KineticSemaphore *sem)
Destorys the KineticSemaphore if it has been signaled.
bool KineticSemaphore_CheckSignaled(KineticSemaphore *sem)
Reports whether the KineticSemaphore has been signaled.
void KineticSemaphore_WaitForSignalAndDestroy(KineticSemaphore *sem)
Blocks until the given semaphore is signaled.
void KineticSemaphore_Signal(KineticSemaphore *sem)
Signals KineticSemaphore.
KineticSemaphore * KineticSemaphore_Create(void)
Creates a KineticSemaphore.