/workspaces/astro/sol3-sdk/cpp/sol3/cpp/event_signal.h Source File

Space-ng SDK: /workspaces/astro/sol3-sdk/cpp/sol3/cpp/event_signal.h Source File
Space-ng SDK
event_signal.h
Go to the documentation of this file.
1 // Copyright (c) Space-ng, inc. All rights reserved.
2 #pragma once
3 
4 #include <chrono>
5 #include <condition_variable>
6 #include <mutex>
7 
8 namespace sol3::core {
9 
15 class EventSignal {
16  public:
17  EventSignal() = default;
18  ~EventSignal() = default;
19 
20  // No copy
21  EventSignal(EventSignal const&) = delete;
22  EventSignal& operator=(EventSignal const&) = delete;
23 
24  // No move
25  EventSignal(EventSignal&&) = delete;
27 
31  bool wait(std::chrono::milliseconds timeout_ms) const {
32  std::unique_lock<std::mutex> lock(mutex_);
33  return cv_.wait_for(lock, timeout_ms, [this, seq = seq_] {
34  // Use != instead of > to be robust to overflow (despite unlikeliness).
35  return seq_ != seq;
36  });
37  }
38 
40  void notify() {
41  std::lock_guard<std::mutex> lock(mutex_);
42  ++seq_;
43  cv_.notify_all(); // Wake all waiting threads
44  }
45 
46  private:
47  mutable std::mutex mutex_;
48  mutable std::condition_variable cv_;
49  // Used to track events. Each time notify() is called, we increment the
50  // sequence number. Any subscriber waiting on an event reads the current
51  // sequence number and checks if it increased while waiting.
52  uint64_t seq_ = 0;
53 };
54 
55 } // namespace sol3::core
Definition: event_signal.h:15
EventSignal(EventSignal &&)=delete
EventSignal(EventSignal const &)=delete
bool wait(std::chrono::milliseconds timeout_ms) const
Definition: event_signal.h:31
EventSignal & operator=(EventSignal const &)=delete
EventSignal & operator=(EventSignal &&)=delete
void notify()
Notify all waiting threads of an event.
Definition: event_signal.h:40
Definition: any_message_input.h:15