Apache Mesos
after.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_AFTER_HPP__
14 #define __PROCESS_AFTER_HPP__
15 
16 #include <memory>
17 
18 #include <process/clock.hpp>
19 #include <process/future.hpp>
20 #include <process/timer.hpp>
21 
22 #include <stout/duration.hpp>
23 #include <stout/nothing.hpp>
24 
25 namespace process {
26 
27 // Provides an abstraction over `Timer` and `Clock::timer` that
28 // completes a future after some duration and lets you attempt to
29 // discard that future.
30 //
31 // This can be used along with `loop` to create "waiting loops", for
32 // example:
33 //
34 // // Wait until a file exists, check for it ever every second.
35 // loop(None(),
36 // []() {
37 // return after(Seconds(1));
38 // },
39 // [=]() {
40 // if (os::exists(file)) -> ControlFlow<Nothing> {
41 // return Break();
42 // }
43 // return Continue();
44 // });
45 inline Future<Nothing> after(const Duration& duration)
46 {
47  std::shared_ptr<Promise<Nothing>> promise(new Promise<Nothing>());
48 
49  Timer timer = Clock::timer(duration, [=]() {
50  promise->set(Nothing());
51  });
52 
53  // Attempt to discard the promise if the future is discarded.
54  //
55  // NOTE: while the future holds a reference to the promise there is
56  // no cicular reference here because even if there are no references
57  // to the Future the timer will eventually fire and we'll set the
58  // promise which will clear the `onDiscard` callback and delete the
59  // reference to Promise.
60  promise->future()
61  .onDiscard([=]() {
62  if (Clock::cancel(timer)) {
63  promise->discard();
64  }
65  });
66 
67  return promise->future();
68 }
69 
70 } // namespace process {
71 
72 #endif // __PROCESS_AFTER_HPP__
Definition: nothing.hpp:16
static bool cancel(const Timer &timer)
Definition: duration.hpp:32
Protocol< PromiseRequest, PromiseResponse > promise
Future< Nothing > after(const Duration &duration)
Definition: after.hpp:45
Result< Process > process(pid_t pid)
Definition: freebsd.hpp:30
Definition: timer.hpp:30
static Timer timer(const Duration &duration, const lambda::function< void()> &thunk)