Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CountDownLatch equivalent

Tags:

java

c++

c++11

For some concurrent programming I could use the Java's CountDownLatch concept. Is there an equivalent for C++11 or what would that concept be called in C++?

What I want is to invoke a function once count has reached zero.

If there is non yet I would write myself a class like the following:

class countdown_function {
public:
  countdown_function( size_t count );
  countdown_function( const countdown_function& ) = default;
  countdown_function( countdown_function&& ) = default;
  countdown_function& operator=( const countdown_function& ) = default;
  countdown_function& operator=( countdown_function&& ) = default;
  // Callback to be invoked
  countdown_function& operator=(std::function<void()> callback);
  countdown_function& operator--();
private:
  struct internal {
    std::function<void()> _callback;
    size_t _count;
    // + some concurrent handling
  };
  // Make sure this class can be copied but still references
  // same state
  std::shared_ptr<internal> _state;
};

Is something similar already available anywhere?

Scenario is:

countdown_function counter( 2 );
counter = [success_callback]() {
  success_callback();
};

startTask1Async( [counter, somework]() {
  somework();
  --counter;
}, errorCallback );

startTask2Async( [counter, otherwork]() {
  otherwork();
  --counter;
}, errorCallback );
like image 641
abergmeier Avatar asked Mar 30 '13 10:03

abergmeier


2 Answers

There is a proposal covering this for the next C++ standard. An implementation is available as part of the google concurrency library.

like image 71
John Schug Avatar answered Oct 22 '22 03:10

John Schug


I've often wished for the same thing. Here's one way to do it ...

#include <chrono>
#include <condition_variable>
#include <mutex>

class CountDownLatch {
public:
    explicit CountDownLatch(const unsigned int count): m_count(count) { }
    virtual ~CountDownLatch() = default;

    void await(void) {
        std::unique_lock<std::mutex> lock(m_mutex);
        if (m_count > 0) {
            m_cv.wait(lock, [this](){ return m_count == 0; });
        }
    }

    template <class Rep, class Period>
    bool await(const std::chrono::duration<Rep, Period>& timeout) {
        std::unique_lock<std::mutex> lock(m_mutex);
        bool result = true;
        if (m_count > 0) {
            result = m_cv.wait_for(lock, timeout, [this](){ return m_count == 0; });
        }

        return result;
    }

    void countDown(void) {
        std::unique_lock<std::mutex> lock(m_mutex);
        if (m_count > 0) {
            m_count--;
            m_cv.notify_all();
        }
    }

    unsigned int getCount(void) {
        std::unique_lock<std::mutex> lock(m_mutex);
        return m_count;
    }

protected:
    std::mutex m_mutex;
    std::condition_variable m_cv;
    unsigned int m_count = 0;
};
like image 30
Eric Peterson Avatar answered Oct 22 '22 04:10

Eric Peterson