Impala
Impalaistheopensource,nativeanalyticdatabaseforApacheHadoop.
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros
promise.h
Go to the documentation of this file.
1 // Copyright 2012 Cloudera Inc.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14 
15 #ifndef IMPALA_UTIL_PROMISE_H
16 #define IMPALA_UTIL_PROMISE_H
17 
18 #include <boost/thread.hpp>
19 
20 #include "common/logging.h"
22 #include "util/time.h"
23 
24 namespace impala {
25 
31 template <typename T>
32 class Promise {
33  public:
34  Promise() : val_is_set_(false) { }
35 
38  void Set(const T& val) {
39  boost::unique_lock<boost::mutex> l(val_lock_);
40  DCHECK(!val_is_set_) << "Called Set(..) twice on the same Promise";
41  val_ = val;
42  val_is_set_ = true;
43 
54  val_set_cond_.notify_all();
55  }
56 
59  const T& Get() {
60  boost::unique_lock<boost::mutex> l(val_lock_);
61  while (!val_is_set_) {
62  val_set_cond_.wait(l);
63  }
64  return val_;
65  }
66 
73  const T& Get(int64_t timeout_millis, bool* timed_out) {
74  DCHECK_GT(timeout_millis, 0);
75  int64_t timeout_micros = timeout_millis * 1000;
76  DCHECK(timed_out != NULL);
77  boost::unique_lock<boost::mutex> l(val_lock_);
78  int64_t start;
79  int64_t now;
80  now = start = MonotonicMicros();
81  while (!val_is_set_ && (now - start) < timeout_micros) {
82  boost::posix_time::microseconds wait_time =
83  boost::posix_time::microseconds(std::max(1L, timeout_micros - (now - start)));
84  val_set_cond_.timed_wait(l, wait_time);
85  now = MonotonicMicros();
86  }
87  *timed_out = !val_is_set_;
88  return val_;
89  }
90 
92  bool IsSet() {
93  boost::lock_guard<boost::mutex> l(val_lock_);
94  return val_is_set_;
95  }
96 
97  private:
100  boost::condition_variable val_set_cond_;
102  boost::mutex val_lock_;
103 
105  T val_;
106 };
107 
108 }
109 
110 #endif
void Set(const T &val)
Definition: promise.h:38
bool val_is_set_
Definition: promise.h:101
const T & Get(int64_t timeout_millis, bool *timed_out)
Definition: promise.h:73
boost::condition_variable val_set_cond_
Definition: promise.h:100
bool IsSet()
Returns whether the value is set.
Definition: promise.h:92
const T & Get()
Definition: promise.h:59
boost::mutex val_lock_
Definition: promise.h:102
int64_t MonotonicMicros()
Definition: time.h:29
T val_
The actual value transferred from producer to consumer.
Definition: promise.h:105