source: flair-src/trunk/lib/FlairCore/src/Semaphore_impl.cpp@ 126

Last change on this file since 126 was 126, checked in by Thomas Fuhrmann, 5 years ago

Add timed semaphore and bool return

File size: 2.3 KB
RevLine 
[117]1// %flair:license{
2// This file is part of the Flair framework distributed under the
3// CECILL-C License, Version 1.0.
4// %flair:license}
5// created: 2016/11/16
6// filename: Semaphore_impl.cpp
7//
8// author: Thomas Fuhrmann
9// Copyright Heudiasyc UMR UTC/CNRS 7253
10//
11// version: $Id: $
12//
13// purpose: Class defining a semaphore implementation
14//
15//
16/*********************************************************************/
17
18#include "Semaphore.h"
19#include "Semaphore_impl.h"
20
21#include <string.h>
[126]22#include <time.h>
[117]23
24using std::string;
25using namespace flair::core;
26
27Semaphore_impl::Semaphore_impl(Semaphore *self, uint32_t initialValue) {
28 this->self = self;
29 int status;
30#ifdef __XENO__
31 status = rt_sem_create(&semaphore, NULL, initialValue, S_FIFO);
32#else
33 status = sem_init(&semaphore, 0, initialValue);
34#endif
35 if (status != 0) {
36 self->Err("error creating semaphore (%s)\n", strerror(-status));
37 }
38}
39
40Semaphore_impl::~Semaphore_impl() {
41 int status;
42#ifdef __XENO__
43 status = rt_sem_delete(&semaphore);
44#else
45 status = sem_destroy(&semaphore);
46#endif
47 if (status != 0)
48 self->Err("error destroying semaphore (%s)\n", strerror(-status));
49}
50
[126]51bool Semaphore_impl::GetSemaphore(Time timeout) {
[117]52 int status;
[126]53 bool returnValue = true;
[117]54#ifdef __XENO__
[126]55 status = rt_sem_p(&semaphore, timeout);
[117]56#else
[126]57 if (timeout != 0) {
58 struct timespec semTimeout;
59 clock_gettime(CLOCK_REALTIME, &semTimeout);
60 semTimeout.tv_sec += timeout / 1000000000ULL;
61 semTimeout.tv_nsec += timeout % 1000000000ULL;
62 if (semTimeout.tv_nsec >= 1000000000ULL) {
63 semTimeout.tv_sec++;
64 semTimeout.tv_nsec -= 1000000000ULL;
65 }
66 status = sem_timedwait(&semaphore, &semTimeout);
67 } else {
68 status = sem_wait(&semaphore);
69 }
[117]70#endif
[126]71 if (status != 0) {
72 if (errno == ETIMEDOUT) {
73 self->Warn("warning : semaphore timedout\n");
74 } else {
75 self->Err("error getting the semaphore (%s)\n", strerror(-status));
76 }
77 returnValue = false;
78 }
79 return returnValue;
[117]80}
81
[126]82bool Semaphore_impl::ReleaseSemaphore(void) {
[117]83 int status;
[126]84 bool returnValue = true;
[117]85#ifdef __XENO__
86 status = rt_sem_v(&semaphore);
87#else
88 status = sem_post(&semaphore);
89#endif
[126]90 if (status != 0) {
[117]91 self->Err("error releasing the semaphore (%s)\n", strerror(-status));
[126]92 returnValue = false;
93 }
94 return returnValue;
[117]95}
Note: See TracBrowser for help on using the repository browser.