blob: fc869d64a4f594c8c326822946c9d45202995267 (
plain)
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
|
//
// Copyright 2019 Ettus Research, a National Instruments brand
//
// SPDX-License-Identifier: GPL-3.0-or-later
//
#include <condition_variable>
#include <chrono>
#include <mutex>
#ifndef INCLUDED_UHDLIB_UTILS_SEMAPHORE_HPP
# define INCLUDED_UHDLIB_UTILS_SEMAPHORE_HPP
namespace uhd {
/*!
* A sempahore built using std::condition_variable
*/
class semaphore
{
public:
void notify()
{
std::unique_lock<std::mutex> lock(_cv_mutex);
_count++;
_cv.notify_one();
}
void wait()
{
std::unique_lock<std::mutex> lock(_cv_mutex);
_cv.wait(lock, [this]() { return this->_count != 0; });
_count--;
}
bool try_wait()
{
std::unique_lock<std::mutex> lock(_cv_mutex);
if (_count != 0) {
_count--;
return true;
}
return false;
}
bool wait_for(size_t timeout_ms)
{
std::chrono::milliseconds timeout(timeout_ms);
std::unique_lock<std::mutex> lock(_cv_mutex);
if (_cv.wait_for(lock, timeout, [this]() { return this->_count != 0; })) {
_count--;
return true;
}
return false;
}
size_t count()
{
std::unique_lock<std::mutex> lock(_cv_mutex);
return _count;
}
private:
std::condition_variable _cv;
std::mutex _cv_mutex;
size_t _count = 0;
};
} // namespace uhd
#endif /* INCLUDED_UHDLIB_UTILS_SEMAPHORE_HPP */
|