C++11 实现信号量Semaphore类

时间:2017-12-03 15:37:03   收藏:0   阅读:1478
 1 #pragma once
 2 #include <mutex>
 3 #include <condition_variable>
 4 class Semaphore
 5 {
 6 public:
 7     explicit Semaphore(unsigned int count); //用无符号数表示信号量资源
 8     ~Semaphore();
 9 public:
10     void wait();
11     void signal();
12 private:
13     int m_count; //计数器必须是有符号数
14     std::mutex m_mutex;
15     std::condition_variable m_condition_variable;
16 };
#include "Semaphore.h"

Semaphore::Semaphore(unsigned int count):m_count(count) {
}

Semaphore::~Semaphore() {
}

void Semaphore::wait() {
    std::unique_lock<std::mutex> unique_lock(m_mutex);
    --m_count;
    while (m_count < 0) {
        m_condition_variable.wait(unique_lock);
    }
}

void Semaphore::signal() {
    std::lock_guard<std::mutex> lg(m_mutex);
    if (++m_count < 1) {
        m_condition_variable.notify_one();
    }
}

//解析:
//if (++m_count < 1) 说明m_count在++之前<0,而m_count的初始值,也即信号量的值为无符号数,只可能>=0。
//那么<0的情况也只可能是因为先调用了wait。因此,便可以确定此时有线程在等待,故可以调用notify_one了。

 

本文参考了http://blog.csdn.net/zdarks/article/details/46994767的代码,并作出适当修改。

评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!