C++0x has no semaphores? How to synchronize threads?

后端 未结 10 1030
无人及你
无人及你 2020-11-22 07:18

Is it true that C++0x will come without semaphores? There are already some questions on Stack Overflow regarding the use of semaphores. I use them (posix semaphores) all the

10条回答
  •  独厮守ぢ
    2020-11-22 07:46

    Based on Maxim Yegorushkin's answer, I tried to make the example in C++11 style.

    #include 
    #include 
    
    class Semaphore {
    public:
        Semaphore (int count_ = 0)
            : count(count_) {}
    
        inline void notify()
        {
            std::unique_lock lock(mtx);
            count++;
            cv.notify_one();
        }
    
        inline void wait()
        {
            std::unique_lock lock(mtx);
    
            while(count == 0){
                cv.wait(lock);
            }
            count--;
        }
    
    private:
        std::mutex mtx;
        std::condition_variable cv;
        int count;
    };
    

提交回复
热议问题