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

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

    In case someone is interested in the atomic version, here is the implementation. The performance is expected better than the mutex & condition variable version.

    class semaphore_atomic
    {
    public:
        void notify() {
            count_.fetch_add(1, std::memory_order_release);
        }
    
        void wait() {
            while (true) {
                int count = count_.load(std::memory_order_relaxed);
                if (count > 0) {
                    if (count_.compare_exchange_weak(count, count-1, std::memory_order_acq_rel, std::memory_order_relaxed)) {
                        break;
                    }
                }
            }
        }
    
        bool try_wait() {
            int count = count_.load(std::memory_order_relaxed);
            if (count > 0) {
                if (count_.compare_exchange_strong(count, count-1, std::memory_order_acq_rel, std::memory_order_relaxed)) {
                    return true;
                }
            }
            return false;
        }
    private:
        std::atomic_int count_{0};
    };
    

提交回复
热议问题