Roc Toolkit internal modules
Roc Toolkit: real-time audio streaming
timer.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/timer.h
10 //! @brief Thread-safe timer.
11 
12 #ifndef ROC_CORE_TIMER_H_
13 #define ROC_CORE_TIMER_H_
14 
15 #include "roc_core/atomic.h"
16 #include "roc_core/noncopyable.h"
17 #include "roc_core/semaphore.h"
18 #include "roc_core/seqlock.h"
19 #include "roc_core/time.h"
20 
21 namespace roc {
22 namespace core {
23 
24 //! Thread-safe timer.
25 class Timer : public NonCopyable<> {
26 public:
27  Timer();
28 
29  //! Set timer deadline.
30  //! Can be called concurrently, but only one concurrent call will succeed.
31  //! Returns false if the call failed because of another concurrent call.
32  //! Is lock-free if Semaphore::post() is so (which is true of modern plarforms).
33  //! Current or future wait_deadline() call will unblock when deadline expires.
34  //! Zero deadline means wake up immediately.
35  //! Nagative deadline means never wake up, until deadline is changed again.
37 
38  //! Wait until deadline expires.
39  //! Should be called from a single thread.
40  //! Assumes that wait_deadline() calls are serialized.
41  //! Deadline may be changed concurrently from other threads.
42  void wait_deadline();
43 
44 private:
45  Semaphore sem_;
46  Atomic<int> sem_post_flag_;
47  Seqlock<nanoseconds_t> deadline_;
48  Seqlock<nanoseconds_t> next_wakeup_;
49 };
50 
51 } // namespace core
52 } // namespace roc
53 
54 #endif // ROC_CORE_TIMER_H_
Atomic.
Base class for non-copyable objects.
Definition: noncopyable.h:23
Thread-safe timer.
Definition: timer.h:25
bool try_set_deadline(nanoseconds_t deadline)
Set timer deadline. Can be called concurrently, but only one concurrent call will succeed....
void wait_deadline()
Wait until deadline expires. Should be called from a single thread. Assumes that wait_deadline() call...
int64_t nanoseconds_t
Nanoseconds.
Definition: time.h:58
Root namespace.
Non-copyable object.
Seqlock.
Time definitions.