1cd139dc7SShuo Chen// excerpts from http://code.google.com/p/muduo/
2cd139dc7SShuo Chen//
3cd139dc7SShuo Chen// Use of this source code is governed by a BSD-style license
4cd139dc7SShuo Chen// that can be found in the License file.
5cd139dc7SShuo Chen//
6cd139dc7SShuo Chen// Author: Shuo Chen (giantchen at gmail dot com)
7cd139dc7SShuo Chen
8cd139dc7SShuo Chen#ifndef MUDUO_BASE_COUNTDOWNLATCH_H
9cd139dc7SShuo Chen#define MUDUO_BASE_COUNTDOWNLATCH_H
10cd139dc7SShuo Chen
11cd139dc7SShuo Chen#include "Mutex.h"
12cd139dc7SShuo Chen#include "Condition.h"
13cd139dc7SShuo Chen
14cd139dc7SShuo Chen#include <boost/noncopyable.hpp>
15cd139dc7SShuo Chen
16cd139dc7SShuo Chennamespace muduo
17cd139dc7SShuo Chen{
18cd139dc7SShuo Chen
19cd139dc7SShuo Chenclass CountDownLatch : boost::noncopyable
20cd139dc7SShuo Chen{
21cd139dc7SShuo Chen public:
22cd139dc7SShuo Chen
23b24dfd25SShuo Chen  explicit CountDownLatch(int count)
24b24dfd25SShuo Chen    : mutex_(),
25b24dfd25SShuo Chen      condition_(mutex_),
26b24dfd25SShuo Chen      count_(count)
27b24dfd25SShuo Chen  {
28b24dfd25SShuo Chen  }
29b24dfd25SShuo Chen
30b24dfd25SShuo Chen  void wait()
31b24dfd25SShuo Chen  {
32b24dfd25SShuo Chen    MutexLockGuard lock(mutex_);
33b24dfd25SShuo Chen    while (count_ > 0)
34b24dfd25SShuo Chen    {
35b24dfd25SShuo Chen      condition_.wait();
36b24dfd25SShuo Chen    }
37b24dfd25SShuo Chen  }
38b24dfd25SShuo Chen
39b24dfd25SShuo Chen  void countDown()
40b24dfd25SShuo Chen  {
41b24dfd25SShuo Chen    MutexLockGuard lock(mutex_);
42b24dfd25SShuo Chen    --count_;
43b24dfd25SShuo Chen    if (count_ == 0)
44b24dfd25SShuo Chen    {
45b24dfd25SShuo Chen      condition_.notifyAll();
46b24dfd25SShuo Chen    }
47b24dfd25SShuo Chen  }
48b24dfd25SShuo Chen
49b24dfd25SShuo Chen  int getCount() const
50b24dfd25SShuo Chen  {
51b24dfd25SShuo Chen    MutexLockGuard lock(mutex_);
52b24dfd25SShuo Chen    return count_;
53b24dfd25SShuo Chen  }
54cd139dc7SShuo Chen
55cd139dc7SShuo Chen private:
56cd139dc7SShuo Chen  mutable MutexLock mutex_;
57cd139dc7SShuo Chen  Condition condition_;
58cd139dc7SShuo Chen  int count_;
59cd139dc7SShuo Chen};
60cd139dc7SShuo Chen
61cd139dc7SShuo Chen}
62cd139dc7SShuo Chen#endif  // MUDUO_BASE_COUNTDOWNLATCH_H
63