Apache Mesos
once.hpp
Go to the documentation of this file.
1 // Licensed under the Apache License, Version 2.0 (the "License");
2 // you may not use this file except in compliance with the License.
3 // You may obtain a copy of the License at
4 //
5 // http://www.apache.org/licenses/LICENSE-2.0
6 //
7 // Unless required by applicable law or agreed to in writing, software
8 // distributed under the License is distributed on an "AS IS" BASIS,
9 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
10 // See the License for the specific language governing permissions and
11 // limitations under the License
12 
13 #ifndef __PROCESS_ONCE_HPP__
14 #define __PROCESS_ONCE_HPP__
15 
16 #include <condition_variable>
17 #include <mutex>
18 
19 #include <stout/synchronized.hpp>
20 
21 namespace process {
22 
23 // Provides a _blocking_ abstraction that's useful for performing a
24 // task exactly once.
25 class Once
26 {
27 public:
28  Once() : started(false), finished(false) {}
29 
30  ~Once() = default;
31 
32  // Returns true if this Once instance has already transitioned to a
33  // 'done' state (i.e., the action you wanted to perform "once" has
34  // been completed). Note that this BLOCKS until Once::done has been
35  // called.
36  bool once()
37  {
38  bool result = false;
39 
40  synchronized (mutex) {
41  if (started) {
42  while (!finished) {
43  synchronized_wait(&cond, &mutex);
44  }
45  result = true;
46  } else {
47  started = true;
48  }
49  }
50 
51  return result;
52  }
53 
54  // Transitions this Once instance to a 'done' state.
55  void done()
56  {
57  synchronized (mutex) {
58  if (started && !finished) {
59  finished = true;
60  cond.notify_all();
61  }
62  }
63  }
64 
65 private:
66  // Not copyable, not assignable.
67  Once(const Once& that);
68  Once& operator=(const Once& that);
69 
70  std::mutex mutex;
71  std::condition_variable cond;
72  bool started;
73  bool finished;
74 };
75 
76 } // namespace process {
77 
78 #endif // __PROCESS_ONCE_HPP__
void synchronized_wait(CV *cv, Lock *lock)
Waits on the condition variable associated with &#39;lock&#39; which has already been synchronized.
~Once()=default
Definition: once.hpp:25
Result< Process > process(pid_t pid)
Definition: freebsd.hpp:30
bool once()
Definition: once.hpp:36
void done()
Definition: once.hpp:55
Once()
Definition: once.hpp:28