muduo 库解析之十:CountDownLatch

源码

CountDownLatch.h

#pragma once
#include "Mutex.h"
#include "Condition.h"
#include "NonCopyable.h"

namespace muduo
{
    class CountDownLatch : public NonCopyable
    {
    public:
        explicit CountDownLatch(int count);

        void wait();
        void count_down();
        int get_count() const;

    private:
        mutable MutexLock mutex_;
        int count_;
        Condition condition_;
    };

} // namespace muduo

CountDownLatch.cc

#include "CountDownLatch.h"

namespace muduo
{
    CountDownLatch::CountDownLatch(int count) : mutex_(), count_(count), condition_(mutex_)
    {
    }

    void CountDownLatch::wait()
    {
        MutexLockGuard lock(mutex_);
        while (count_ > 0)
        {
            condition_.wait();
        }
    }

    void CountDownLatch::count_down()
    {
        MutexLockGuard lock(mutex_);
        --count_;
        if (count_ == 0)
        {
            condition_.notify_all();
        }
    }

    int CountDownLatch::get_count() const
    {
        MutexLockGuard lock(mutex_);
        return count_;
    }
}
上一篇:第 2 节 Mustache、v-bind、计算属性、v-on、v-if、v-for、响应式方法


下一篇:初中生C++笔记(二)