CernVM-FS  2.12.0
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Pages
future.h
Go to the documentation of this file.
1 
5 #ifndef CVMFS_UTIL_FUTURE_H_
6 #define CVMFS_UTIL_FUTURE_H_
7 
8 #include <pthread.h>
9 
10 #include <cassert>
11 
12 #include "util/mutex.h"
13 #include "util/single_copy.h"
14 
15 #ifdef CVMFS_NAMESPACE_GUARD
16 namespace CVMFS_NAMESPACE_GUARD {
17 #endif
18 
31 template <typename T>
32 class Future : SingleCopy {
33  public:
34  Future() : object_was_set_(false) {
35  int retval = pthread_mutex_init(&mutex_, NULL);
36  assert(retval == 0);
37  retval = pthread_cond_init(&object_set_, NULL);
38  assert(retval == 0);
39  }
40 
41  ~Future() {
42  int retval = pthread_cond_destroy(&object_set_);
43  assert(retval == 0);
44  retval = pthread_mutex_destroy(&mutex_);
45  assert(retval == 0);
46  }
47 
53  void Set(const T &object) {
54  MutexLockGuard guard(mutex_);
55  assert(!object_was_set_);
56  object_ = object;
57  object_was_set_ = true;
58  pthread_cond_broadcast(&object_set_);
59  }
60 
66  T& Get() {
67  Wait();
68  return object_;
69  }
70 
71  const T& Get() const {
72  Wait();
73  return object_;
74  }
75 
76  private:
77  void Wait() const {
78  MutexLockGuard guard(mutex_);
79  while (!object_was_set_) {
80  pthread_cond_wait(&object_set_, &mutex_);
81  }
82  }
83 
85  mutable pthread_mutex_t mutex_;
86  mutable pthread_cond_t object_set_;
88 };
89 
90 #ifdef CVMFS_NAMESPACE_GUARD
91 } // namespace CVMFS_NAMESPACE_GUARD
92 #endif
93 
94 #endif // CVMFS_UTIL_FUTURE_H_
void Wait() const
Definition: future.h:77
Definition: future.h:32
bool object_was_set_
Definition: future.h:87
pthread_cond_t object_set_
Definition: future.h:86
T object_
Definition: future.h:84
assert((mem||(size==0))&&"Out Of Memory")
void Set(const T &object)
Definition: future.h:53
T & Get()
Definition: future.h:66
Future()
Definition: future.h:34
pthread_mutex_t mutex_
Definition: future.h:85
Definition: mutex.h:42
~Future()
Definition: future.h:41
const T & Get() const
Definition: future.h:71