summaryrefslogtreecommitdiff
path: root/chromium/base/barrier_closure.cc
blob: d7c4f1ff10beffeec188e7f9a6f0841349ad5a4a (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
// 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 <utility>

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

namespace base {
namespace {

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

 private:
  AtomicRefCount num_callbacks_left_;
  OnceClosure done_closure_;
};

BarrierInfo::BarrierInfo(int num_callbacks, OnceClosure done_closure)
    : num_callbacks_left_(num_callbacks),
      done_closure_(std::move(done_closure)) {}

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

}  // namespace

RepeatingClosure BarrierClosure(int num_callbacks_left,
                                OnceClosure done_closure) {
  DCHECK_GE(num_callbacks_left, 0);

  if (num_callbacks_left == 0)
    std::move(done_closure).Run();

  return BindRepeating(
      &BarrierInfo::Run,
      Owned(new BarrierInfo(num_callbacks_left, std::move(done_closure))));
}

}  // namespace base