Subordination
A framework for distributed programming
thread_context.hh
1 #ifndef SUBORDINATION_PPL_THREAD_CONTEXT_HH
2 #define SUBORDINATION_PPL_THREAD_CONTEXT_HH
3 
4 #include <mutex>
5 #include <unistdx/base/simple_lock>
6 #include <unistdx/ipc/thread_semaphore>
7 
8 namespace sbn {
9 
10  struct Thread_context {
11 
12  typedef std::mutex mutex_type;
13  typedef sys::thread_semaphore sem_type;
14 
15  inline void
16  register_thread() noexcept {
17  ++this->_nthreads;
18  ++this->_saved_nthreads;
19  }
20 
21  inline void
22  lock() {
23  this->_mtx.lock();
24  }
25 
26  inline void
27  unlock() {
28  this->_mtx.unlock();
29  }
30 
31  template <class Lock>
32  void
33  wait(Lock& lock) {
34  if (--this->_nthreads == 0) {
35  this->_nthreads = this->_saved_nthreads;
36  for (int i=0; i<this->_nthreads; ++i) {
37  this->_semaphore.notify_one();
38  }
39  } else {
40  this->_semaphore.wait(lock);
41  }
42  }
43 
44  private:
45  volatile int _nthreads = 0;
46  volatile int _saved_nthreads = 0;
47  mutex_type _mtx;
48  sem_type _semaphore;
49  };
50 
51  typedef sys::simple_lock<Thread_context> Thread_context_guard;
52 
53  namespace this_thread {
54 
55  extern Thread_context context;
56 
57  }
58 
59 }
60 
61 #endif // vim:filetype=cpp
T unlock(T... args)
T lock(T... args)
Definition: thread_context.hh:10