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"
8 #include "testing/gtest/include/gtest/gtest.h"
12 void Increment(int* count
) { (*count
)++; }
14 TEST(BarrierClosureTest
, RunImmediatelyForZeroClosures
) {
16 base::Closure
done_closure(base::Bind(&Increment
, base::Unretained(&count
)));
18 base::Closure barrier_closure
= base::BarrierClosure(0, done_closure
);
22 TEST(BarrierClosureTest
, RunAfterNumClosures
) {
24 base::Closure
done_closure(base::Bind(&Increment
, base::Unretained(&count
)));
26 base::Closure barrier_closure
= base::BarrierClosure(2, done_closure
);
29 barrier_closure
.Run();
32 barrier_closure
.Run();
36 class DestructionIndicator
{
38 // Sets |*destructed| to true in destructor.
39 DestructionIndicator(bool* destructed
) : destructed_(destructed
) {
43 ~DestructionIndicator() { *destructed_
= true; }
51 TEST(BarrierClosureTest
, ReleasesDoneClosureWhenDone
) {
52 bool done_destructed
= false;
53 base::Closure barrier_closure
= base::BarrierClosure(
54 1, base::Bind(&DestructionIndicator::DoNothing
,
55 base::Owned(new DestructionIndicator(&done_destructed
))));
56 EXPECT_FALSE(done_destructed
);
57 barrier_closure
.Run();
58 EXPECT_TRUE(done_destructed
);
61 void ResetBarrierClosure(base::Closure
* closure
) {
62 *closure
= base::Closure();
65 // Tests a case when |done_closure| resets a |barrier_closure|.
66 // |barrier_closure| is a Closure holding the |done_closure|. |done_closure|
67 // holds a pointer back to the |barrier_closure|. When |barrier_closure| is
68 // Run() it calls ResetBarrierClosure() which erases the |barrier_closure| while
69 // still inside of its Run(). The Run() implementation (in base::BarrierClosure)
70 // must not try use itself after executing ResetBarrierClosure() or this test
71 // would crash inside Run().
72 TEST(BarrierClosureTest
, KeepingClosureAliveUntilDone
) {
73 base::Closure barrier_closure
;
74 base::Closure done_closure
=
75 base::Bind(ResetBarrierClosure
, &barrier_closure
);
76 barrier_closure
= base::BarrierClosure(1, done_closure
);
77 barrier_closure
.Run();