Newer
Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
/**
* @author Daniel Mueller
*
* @copyright Copyright 2021 Daniel Mueller. All rights reserved.
*/
#include "semaphore.hpp"
#include <stdexcept>
#include <ctime>
Semaphore::Semaphore(int initialValue)
{
_semaphore = new sem_t;
sem_init(_semaphore, 0, initialValue);
}
Semaphore::Semaphore(Semaphore && other)
: _semaphore{other._semaphore}
{
other._semaphore = nullptr;
}
Semaphore & Semaphore::operator=(Semaphore && other)
{
if (&other != this)
{
sem_destroy(_semaphore);
delete _semaphore;
_semaphore = other._semaphore;
other._semaphore = nullptr;
}
return *this;
}
Semaphore::~Semaphore()
{
sem_destroy(_semaphore);
delete _semaphore;
}
void Semaphore::post()
{
if (_semaphore == nullptr)
throw std::runtime_error("Semaphore used after move");
sem_post(_semaphore);
}
void Semaphore::wait()
{
if (_semaphore == nullptr)
throw std::runtime_error("Semaphore used after move");
sem_wait(_semaphore);
}
bool Semaphore::tryWait()
{
if (_semaphore == nullptr)
throw std::runtime_error("Semaphore used after move");
return (sem_trywait(_semaphore) == 0);
}
bool Semaphore::timedWait(long ms)
{
if (_semaphore == nullptr)
throw std::runtime_error("Semaphore used after move");
// Split the milliseconds into full seconds and leftover nanoseconds
int secs = ms / 1000;
int nsecs = (ms % 1000) * 1000000L;
timespec ts;
// sem_timedwait need the absolute timestamp when to stop waiting, so get
// the current timestamp and add the wait time.
clock_gettime(CLOCK_REALTIME, &ts);
ts.tv_sec += secs;
ts.tv_nsec += nsecs;
return (sem_timedwait(_semaphore, &ts) == 0);
}
int Semaphore::getValue()
{
if (_semaphore == nullptr)
throw std::runtime_error("Semaphore used after move");
int val;
sem_getvalue(_semaphore, &val);
return val;
}