back

by ibobev·5y ago·view on hn ↗
Does someone have any idea why latches do not have also count up operation alongside count down? In one of my previous jobs, I implemented a latch with a mutex, condition variable, and a counter and I supported also count up. It seems to work OK and count up was an essential operation for the use case I had needed it.

    class ThreadLatch
    {
    public:
        ThreadLatch(std::size_t count = 0)
            : _count(count) {}

        void inc()
        {
            std::lock_guard<std::mutex> lock(_mutex);
            ++_count;
        }

        void dec()
        {
            std::lock_guard<std::mutex> lock(_mutex);
            assert(0 != _count);
            --_count;
            if(0 == _count)
            {
                _condition.notify_all();
            }
        }

        void wait()
        {
            std::unique_lock<std::mutex> lock(_mutex);
            while(_count > 0)
            {
                _condition.wait(lock);
            }
        }

    private:
        std::mutex _mutex;
        std::condition_variable _condition;
        std::size_t _count;
    };