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

后端 未结 10 837
无人及你
无人及你 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:36

    You can easily build one from a mutex and a condition variable:

    #include 
    #include 
    
    class semaphore
    {
    private:
        std::mutex mutex_;
        std::condition_variable condition_;
        unsigned long count_ = 0; // Initialized as locked.
    
    public:
        void notify() {
            std::lock_guard lock(mutex_);
            ++count_;
            condition_.notify_one();
        }
    
        void wait() {
            std::unique_lock lock(mutex_);
            while(!count_) // Handle spurious wake-ups.
                condition_.wait(lock);
            --count_;
        }
    
        bool try_wait() {
            std::lock_guard lock(mutex_);
            if(count_) {
                --count_;
                return true;
            }
            return false;
        }
    };
    

提交回复
热议问题