Roc Toolkit internal modules
Roc Toolkit: real-time audio streaming
semaphore.h
Go to the documentation of this file.
1 /*
2  * Copyright (c) 2020 Roc Streaming authors
3  *
4  * This Source Code Form is subject to the terms of the Mozilla Public
5  * License, v. 2.0. If a copy of the MPL was not distributed with this
6  * file, You can obtain one at http://mozilla.org/MPL/2.0/.
7  */
8 
9 //! @file roc_core/target_posix_ext/roc_core/semaphore.h
10 //! @brief Semaphore.
11 
12 #ifndef ROC_CORE_SEMAPHORE_H_
13 #define ROC_CORE_SEMAPHORE_H_
14 
15 #include <semaphore.h>
16 
17 #include "roc_core/atomic.h"
18 #include "roc_core/attributes.h"
19 #include "roc_core/noncopyable.h"
20 #include "roc_core/time.h"
21 
22 namespace roc {
23 namespace core {
24 
25 //! Semaphore.
26 class Semaphore : public NonCopyable<> {
27 public:
28  //! Initialize semaphore with given counter.
29  explicit Semaphore(unsigned counter = 0);
30 
31  ~Semaphore();
32 
33  //! Wait until the counter becomes non-zero, decrement it, and return true.
34  //! If deadline expires before the counter becomes non-zero, returns false.
35  //! Deadline should be in the same time domain as core::timestamp().
37 
38  //! Wait until the counter becomes non-zero, decrement it, and return.
39  void wait();
40 
41  //! Increment counter and wake up blocked waits.
42  //! This method is lock-free at least on recent glibc and musl versions
43  //! (which implement POSIX semaphores using a futex and an atomic).
44  void post();
45 
46 private:
47  sem_t sem_;
48  Atomic<int> guard_;
49 };
50 
51 } // namespace core
52 } // namespace roc
53 
54 #endif // ROC_CORE_SEMAPHORE_H_
Atomic.
Compiler attributes.
#define ROC_ATTR_NODISCARD
Emit warning if function result is not checked.
Definition: attributes.h:31
Semaphore(unsigned counter=0)
Initialize semaphore with given counter.
ROC_ATTR_NODISCARD bool timed_wait(nanoseconds_t deadline)
Wait until the counter becomes non-zero, decrement it, and return true. If deadline expires before th...
void wait()
Wait until the counter becomes non-zero, decrement it, and return.
void post()
Increment counter and wake up blocked waits. This method is lock-free at least on recent glibc and mu...
int64_t nanoseconds_t
Nanoseconds.
Definition: time.h:58
Root namespace.
Non-copyable object.
Semaphore.
Time definitions.