对于一些并发编程,我可以使用 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;
};
类似的东西是否已经在任何地方可用?
场景是:
countdown_function counter( 2 );
counter = [success_callback]() {
success_callback();
};
startTask1Async( [counter, somework]() {
somework();
--counter;
}, errorCallback );
startTask2Async( [counter, otherwork]() {
otherwork();
--counter;
}, errorCallback );