1 #pragmaOnce2#include <mutex>3#include <condition_variable>4 classSemaphore5 {6 Public:7 ExplicitSemaphore (unsignedintcount);//representing semaphore resources with unsigned numbers8~Semaphore ();9 Public:Ten voidwait (); One voidsignal (); A Private: - intM_count;//The counter must be a signed number - Std::mutex M_mutex; the std::condition_variable m_condition_variable; -};
#include"Semaphore.h"Semaphore::semaphore (unsignedintcount): M_count (count) {}semaphore::~Semaphore () {}voidsemaphore::wait () {Std::unique_lock<std::mutex>Unique_lock (M_mutex); --M_count; while(M_count <0) {m_condition_variable.wait (unique_lock); }}voidsemaphore::signal () {Std::lock_guard<std::mutex>LG (M_MUTEX); if(++m_count <1) {m_condition_variable.notify_one (); }}//parsing://if(++m_count < 1) shows that m_count before + + <0, and the initial value of M_count, that is, the value of the semaphore is an unsigned number, only possible >=0. //then the <0 is only possible because the wait is called first. Therefore, you can determine that the thread is waiting at this time, so you can call Notify_one.
This article references the code of the http://blog.csdn.net/zdarks/article/details/46994767 and makes the appropriate modifications.
C++11 realization of Semaphore Semaphore class