Thrill  0.1
shared_state.hpp
Go to the documentation of this file.
1 /*******************************************************************************
2  * thrill/common/shared_state.hpp
3  *
4  * Copied and modified from STXXL https://github.com/stxxl/stxxl, which is
5  * distributed under the Boost Software License, Version 1.0.
6  *
7  * Part of Project Thrill - http://project-thrill.org
8  *
9  * Copyright (C) 2002 Roman Dementiev <[email protected]>
10  * Copyright (C) 2008 Andreas Beckmann <[email protected]>
11  * Copyright (C) 2013 Timo Bingmann <[email protected]>
12  *
13  * All rights reserved. Published under the BSD-2 license in the LICENSE file.
14  ******************************************************************************/
15 
16 #pragma once
17 #ifndef THRILL_COMMON_SHARED_STATE_HEADER
18 #define THRILL_COMMON_SHARED_STATE_HEADER
19 
20 #include <condition_variable>
21 #include <mutex>
22 
23 namespace thrill {
24 namespace common {
25 
26 template <typename ValueType = size_t>
28 {
29  using value_type = ValueType;
30 
31  //! mutex for condition variable
32  std::mutex mutex_;
33 
34  //! condition variable
35  std::condition_variable cv_;
36 
37  //! current state
39 
40 public:
41  explicit SharedState(const value_type& s)
42  : state_(s)
43  { }
44 
45  //! non-copyable: delete copy-constructor
46  SharedState(const SharedState&) = delete;
47  //! non-copyable: delete assignment operator
48  SharedState& operator = (const SharedState&) = delete;
49 
50  void set_to(const value_type& new_state) {
51  std::unique_lock<std::mutex> lock(mutex_);
52  state_ = new_state;
53  lock.unlock();
54  cv_.notify_all();
55  }
56 
57  void wait_for(const value_type& needed_state) {
58  std::unique_lock<std::mutex> lock(mutex_);
59  while (needed_state != state_)
60  cv_.wait(lock);
61  }
62 
64  std::unique_lock<std::mutex> lock(mutex_);
65  return state_;
66  }
67 };
68 
69 } // namespace common
70 } // namespace thrill
71 
72 #endif // !THRILL_COMMON_SHARED_STATE_HEADER
73 
74 /******************************************************************************/
std::mutex mutex_
mutex for condition variable
SharedState(const value_type &s)
void set_to(const value_type &new_state)
void wait_for(const value_type &needed_state)
std::condition_variable cv_
condition variable
value_type state_
current state
SharedState & operator=(const SharedState &)=delete
non-copyable: delete assignment operator