1 // Copyright (c) 2012 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/threading/worker_pool.h"
8 #include "base/bind_helpers.h"
9 #include "base/location.h"
10 #include "base/message_loop.h"
11 #include "base/test/test_timeouts.h"
12 #include "base/time.h"
13 #include "base/threading/thread_checker_impl.h"
14 #include "base/synchronization/waitable_event.h"
15 #include "testing/gtest/include/gtest/gtest.h"
16 #include "testing/platform_test.h"
18 typedef PlatformTest WorkerPoolTest
;
24 class PostTaskAndReplyTester
25 : public base::RefCountedThreadSafe
<PostTaskAndReplyTester
> {
27 PostTaskAndReplyTester() : finished_(false), test_event_(false, false) {}
30 ASSERT_TRUE(thread_checker_
.CalledOnValidThread());
31 WorkerPool::PostTaskAndReply(
33 base::Bind(&PostTaskAndReplyTester::OnWorkerThread
, this),
34 base::Bind(&PostTaskAndReplyTester::OnOriginalThread
, this),
40 void OnWorkerThread() {
41 // We're not on the original thread.
42 EXPECT_FALSE(thread_checker_
.CalledOnValidThread());
47 void OnOriginalThread() {
48 EXPECT_TRUE(thread_checker_
.CalledOnValidThread());
52 bool finished() const {
57 friend class base::RefCountedThreadSafe
<PostTaskAndReplyTester
>;
58 ~PostTaskAndReplyTester() {}
61 WaitableEvent test_event_
;
63 // The Impl version performs its checks even in release builds.
64 ThreadCheckerImpl thread_checker_
;
69 TEST_F(WorkerPoolTest
, PostTask
) {
70 WaitableEvent
test_event(false, false);
71 WaitableEvent
long_test_event(false, false);
73 WorkerPool::PostTask(FROM_HERE
,
74 base::Bind(&WaitableEvent::Signal
,
75 base::Unretained(&test_event
)),
77 WorkerPool::PostTask(FROM_HERE
,
78 base::Bind(&WaitableEvent::Signal
,
79 base::Unretained(&long_test_event
)),
83 long_test_event
.Wait();
86 #if defined(OS_WIN) || defined(OS_LINUX)
87 // Flaky on Windows and Linux (http://crbug.com/130337)
88 #define MAYBE_PostTaskAndReply DISABLED_PostTaskAndReply
90 #define MAYBE_PostTaskAndReply PostTaskAndReply
93 TEST_F(WorkerPoolTest
, MAYBE_PostTaskAndReply
) {
94 MessageLoop message_loop
;
95 scoped_refptr
<PostTaskAndReplyTester
> tester(new PostTaskAndReplyTester());
98 const TimeDelta kMaxDuration
= TestTimeouts::tiny_timeout();
99 TimeTicks start
= TimeTicks::Now();
100 while (!tester
->finished() && TimeTicks::Now() - start
< kMaxDuration
) {
102 // Ensure that the other thread has a chance to run even on a single-core
106 MessageLoop::current()->RunUntilIdle();
108 EXPECT_TRUE(tester
->finished());