• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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.
4 
5 #include "base/barrier_closure.h"
6 
7 #include <utility>
8 
9 #include "base/atomic_ref_count.h"
10 #include "base/bind.h"
11 #include "base/memory/ptr_util.h"
12 
13 namespace base {
14 namespace {
15 
16 // Maintains state for a BarrierClosure.
17 class BarrierInfo {
18  public:
19   BarrierInfo(int num_callbacks_left, OnceClosure done_closure);
20   void Run();
21 
22  private:
23   AtomicRefCount num_callbacks_left_;
24   OnceClosure done_closure_;
25 };
26 
BarrierInfo(int num_callbacks,OnceClosure done_closure)27 BarrierInfo::BarrierInfo(int num_callbacks, OnceClosure done_closure)
28     : num_callbacks_left_(num_callbacks),
29       done_closure_(std::move(done_closure)) {}
30 
Run()31 void BarrierInfo::Run() {
32   DCHECK(!num_callbacks_left_.IsZero());
33   if (!num_callbacks_left_.Decrement())
34     std::move(done_closure_).Run();
35 }
36 
37 }  // namespace
38 
BarrierClosure(int num_callbacks_left,OnceClosure done_closure)39 RepeatingClosure BarrierClosure(int num_callbacks_left,
40                                 OnceClosure done_closure) {
41   DCHECK_GE(num_callbacks_left, 0);
42 
43   if (num_callbacks_left == 0)
44     std::move(done_closure).Run();
45 
46   return BindRepeating(
47       &BarrierInfo::Run,
48       Owned(new BarrierInfo(num_callbacks_left, std::move(done_closure))));
49 }
50 
51 }  // namespace base
52