1 // Copyright 2013 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "base/barrier_closure.h"
9 #include "base/atomic_ref_count.h"
10 #include "base/bind.h"
11 #include "base/memory/ptr_util.h"
12 #include "base/numerics/safe_conversions.h"
17 // Maintains state for a BarrierClosure.
20 BarrierInfo(size_t num_callbacks_left, OnceClosure done_closure);
24 AtomicRefCount num_callbacks_left_;
25 OnceClosure done_closure_;
28 BarrierInfo::BarrierInfo(size_t num_callbacks, OnceClosure done_closure)
29 : num_callbacks_left_(checked_cast<int>(num_callbacks)),
30 done_closure_(std::move(done_closure)) {}
32 void BarrierInfo::Run() {
33 DCHECK(!num_callbacks_left_.IsZero());
34 if (!num_callbacks_left_.Decrement())
35 std::move(done_closure_).Run();
38 void ShouldNeverRun() {
44 RepeatingClosure BarrierClosure(size_t num_callbacks_left,
45 OnceClosure done_closure) {
46 if (num_callbacks_left == 0) {
47 std::move(done_closure).Run();
48 return BindRepeating(&ShouldNeverRun);
51 return BindRepeating(&BarrierInfo::Run,
52 std::make_unique<BarrierInfo>(num_callbacks_left,
53 std::move(done_closure)));