FairMQ  1.4.14
C++ Message Queuing Library and Framework
StateQueue.h
1 /********************************************************************************
2  * Copyright (C) 2019 GSI Helmholtzzentrum fuer Schwerionenforschung GmbH *
3  * *
4  * This software is distributed under the terms of the *
5  * GNU Lesser General Public Licence (LGPL) version 3, *
6  * copied verbatim in the file "LICENSE" *
7  ********************************************************************************/
8 
9 #ifndef FAIRMQSTATEQUEUE_H_
10 #define FAIRMQSTATEQUEUE_H_
11 
12 #include <fairmq/States.h>
13 
14 #include <queue>
15 #include <mutex>
16 #include <chrono>
17 #include <utility> // pair
18 #include <condition_variable>
19 
20 namespace fair
21 {
22 namespace mq
23 {
24 
26 {
27  public:
28  StateQueue() {}
29  ~StateQueue() {}
30 
31  fair::mq::State WaitForNext()
32  {
33  std::unique_lock<std::mutex> lock(fMtx);
34  while (fStates.empty()) {
35  fCV.wait_for(lock, std::chrono::milliseconds(50));
36  }
37 
38  fair::mq::State state = fStates.front();
39 
40  if (state == fair::mq::State::Error) {
41  throw DeviceErrorState("Controlled device transitioned to error state.");
42  }
43 
44  fStates.pop();
45  return state;
46  }
47 
48  template<typename Rep, typename Period>
49  std::pair<bool, fair::mq::State> WaitForNext(std::chrono::duration<Rep, Period> const& duration)
50  {
51  std::unique_lock<std::mutex> lock(fMtx);
52  fCV.wait_for(lock, duration);
53 
54  if (fStates.empty()) {
55  return { false, fair::mq::State::Ok };
56  }
57 
58  fair::mq::State state = fStates.front();
59 
60  if (state == fair::mq::State::Error) {
61  throw DeviceErrorState("Controlled device transitioned to error state.");
62  }
63 
64  fStates.pop();
65  return { true, state };
66  }
67 
68  void WaitForState(fair::mq::State state) { while (WaitForNext() != state) {} }
69 
70  void Push(fair::mq::State state)
71  {
72  {
73  std::lock_guard<std::mutex> lock(fMtx);
74  fStates.push(state);
75  }
76  fCV.notify_all();
77  }
78 
79  void Clear()
80  {
81  std::lock_guard<std::mutex> lock(fMtx);
82  fStates = std::queue<fair::mq::State>();
83  }
84 
85  private:
86  std::queue<fair::mq::State> fStates;
87  std::mutex fMtx;
88  std::condition_variable fCV;
89 };
90 
91 } // namespace mq
92 } // namespace fair
93 
94 #endif /* FAIRMQSTATEQUEUE_H_ */
Definition: States.h:61
Definition: StateQueue.h:25
Tools for interfacing containers to the transport via polymorphic allocators.
Definition: DeviceRunner.h:23

privacy