C++11 实现信号量Semaphore类

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

Semaphore.h

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

Semaphore.cpp

 1 //Semaphore.cpp
 2 
 3 #include "Semaphore.h"
 4 
 5 Semaphore::Semaphore(unsigned int count):m_count(count) {
 6 }
 7 
 8 Semaphore::~Semaphore() {
 9 }
10 
11 void Semaphore::wait() {
12     std::unique_lock<std::mutex> unique_lock(m_mutex);
13     --m_count;
14     while (m_count < 0) {
15         m_condition_variable.wait(unique_lock);
16     }
17 }
18 
19 void Semaphore::signal() {
20     std::lock_guard<std::mutex> lg(m_mutex);
21     if (++m_count < 1) {
22         m_condition_variable.notify_one();
23     }
24 }
25 
26 //解析:
27 //if (++m_count < 1) 说明m_count在++之前<0,而m_count的初始值,也即信号量的值为无符号数,只可能>=0。
28 //那么<0的情况也只可能是因为先调用了wait。因此,便可以确定此时有线程在等待,故可以调用notify_one了。
原文地址:https://www.cnblogs.com/waterfall/p/7966116.html