CountDownLatch等价物

abe*_*ier 7 c++ java c++11

对于某些并发编程,我可以使用Java的CountDownLatch概念.是否存在C++ 11的等价物或者在C++中调用该概念的内容?

我想要的是一旦计数达到零就调用一个函数.

如果还没有,我会写一个类如下的类:

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;
};
Run Code Online (Sandbox Code Playgroud)

类似的东西已经可以在任

场景是:

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

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

startTask2Async( [counter, otherwork]() {
  otherwork();
  --counter;
}, errorCallback );
Run Code Online (Sandbox Code Playgroud)

Joh*_*hug 4

下一个 C++ 标准中有一项涵盖此内容的提案。一个实现可作为google 并发库的一部分提供。