[ create a new paste ] login | about

Link: http://codepad.org/E8kd2Eb8    [ raw code | fork ]

C++, pasted on Apr 21:
/// A C++ implementation of Java's CountDownLatch.
/// A synchronization aid that allows one or more threads to wait
/// until a set of operations being performed in other threads complete.
class countdown_latch
{
public:
    /// Constructs a countdown latch with a given count.
    countdown_latch( std::size_t count_ )
        : count( count_ )
    {
    }

    /// Blocks until the latch has counted down to zero.
    void wait()
    {
        std::unique_lock<std::mutex> lock( mutex );
        while ( count > 0 )
        {
            cond_var.wait( lock );
        }
    }

    /// @todo add wait_for and wait_until

    /// Decrement the count and notify anyone waiting if we reach zero.
    /// @note count must be greater than 0 or undefined behavior
    void count_down()
    {
        std::lock_guard<std::mutex> lock(mutex);
        assert( count );
        if ( --count == 0 )
        {
            cond_var.notify_all();
        }
    }


private:
    std::size_t count;
    std::mutex mutex;
    std::condition_variable cond_var;
};


Create a new paste based on this one


Comments: