summaryrefslogtreecommitdiffstats
path: root/base/barrier_closure.cc
blob: 5abe2bfaec252acb65c0ab7ea74275c3cf96de44 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "base/barrier_closure.h"

#include "base/atomic_ref_count.h"
#include "base/bind.h"

namespace {

// Maintains state for a BarrierClosure.
class BarrierInfo {
 public:
  BarrierInfo(int num_callbacks_left, const base::Closure& done_closure);
  void Run();

 private:
  base::AtomicRefCount num_callbacks_left_;
  base::Closure done_closure_;
};

BarrierInfo::BarrierInfo(int num_callbacks, const base::Closure& done_closure)
    : num_callbacks_left_(num_callbacks),
      done_closure_(done_closure) {
}

void BarrierInfo::Run() {
  DCHECK(!base::AtomicRefCountIsZero(&num_callbacks_left_));
  if (!base::AtomicRefCountDec(&num_callbacks_left_)) {
    done_closure_.Run();
    done_closure_.Reset();
  }
}

}  // namespace

namespace base {

base::Closure BarrierClosure(int num_callbacks_left,
                             const base::Closure& done_closure) {
  DCHECK(num_callbacks_left >= 0);

  if (num_callbacks_left == 0)
    done_closure.Run();

  return base::Bind(&BarrierInfo::Run,
                    base::Owned(
                        new BarrierInfo(num_callbacks_left, done_closure)));
}

}  // namespace base