Thrill  0.1
shared_state.hpp
Go to the documentation of this file.
1 /***************************************************************************
2  * foxxll/common/shared_state.hpp
3  *
4  * Part of FOXXLL. See http://foxxll.org
5  *
6  * Copyright (C) 2002 Roman Dementiev <[email protected]>
7  * Copyright (C) 2008 Andreas Beckmann <[email protected]>
8  * Copyright (C) 2013 Timo Bingmann <[email protected]>
9  *
10  * Distributed under the Boost Software License, Version 1.0.
11  * (See accompanying file LICENSE_1_0.txt or copy at
12  * http://www.boost.org/LICENSE_1_0.txt)
13  **************************************************************************/
14 
15 #ifndef FOXXLL_COMMON_SHARED_STATE_HEADER
16 #define FOXXLL_COMMON_SHARED_STATE_HEADER
17 
18 #include <condition_variable>
19 #include <mutex>
20 
21 namespace foxxll {
22 
23 template <typename ValueType = size_t>
25 {
26  using value_type = ValueType;
27 
28  //! mutex for condition variable
29  std::mutex mutex_;
30 
31  //! condition variable
32  std::condition_variable cv_;
33 
34  //! current shared_state
36 
37 public:
38  explicit shared_state(const value_type& s)
39  : state_(s) { }
40 
41  //! non-copyable: delete copy-constructor
42  shared_state(const shared_state&) = delete;
43  //! non-copyable: delete assignment operator
44  shared_state& operator = (const shared_state&) = delete;
45 
46  void set_to(const value_type& new_state)
47  {
48  std::unique_lock<std::mutex> lock(mutex_);
49  state_ = new_state;
50  lock.unlock();
51  cv_.notify_all();
52  }
53 
54  void wait_for(const value_type& needed_state)
55  {
56  std::unique_lock<std::mutex> lock(mutex_);
57  while (needed_state != state_)
58  cv_.wait(lock);
59  }
60 
62  {
63  std::unique_lock<std::mutex> lock(mutex_);
64  return state_;
65  }
66 };
67 
68 } // namespace foxxll
69 
70 #endif // !FOXXLL_COMMON_SHARED_STATE_HEADER
71 
72 /**************************************************************************/
std::condition_variable cv_
condition variable
void set_to(const value_type &new_state)
std::mutex mutex_
mutex for condition variable
shared_state & operator=(const shared_state &)=delete
non-copyable: delete assignment operator
value_type operator()()
value_type state_
current shared_state
FOXXLL library namespace
void wait_for(const value_type &needed_state)
shared_state(const value_type &s)