C++11 realization of Semaphore Semaphore class

Source: Internet
Author: User
Tags mutex semaphore

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.