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/message_loop.h"
11 #include "base/run_loop.h"
12 #include "base/synchronization/waitable_event.h"
13 #include "base/test/test_timeouts.h"
14 #include "base/threading/thread_checker_impl.h"
15 #include "base/time/time.h"
16 #include "testing/gtest/include/gtest/gtest.h"
17 #include "testing/platform_test.h"
19 typedef PlatformTest WorkerPoolTest
;
25 class PostTaskAndReplyTester
26 : public base::RefCountedThreadSafe
<PostTaskAndReplyTester
> {
28 PostTaskAndReplyTester() : finished_(false), test_event_(false, false) {}
31 ASSERT_TRUE(thread_checker_
.CalledOnValidThread());
32 WorkerPool::PostTaskAndReply(
34 base::Bind(&PostTaskAndReplyTester::OnWorkerThread
, this),
35 base::Bind(&PostTaskAndReplyTester::OnOriginalThread
, this),
41 void OnWorkerThread() {
42 // We're not on the original thread.
43 EXPECT_FALSE(thread_checker_
.CalledOnValidThread());
48 void OnOriginalThread() {
49 EXPECT_TRUE(thread_checker_
.CalledOnValidThread());
53 bool finished() const {
58 friend class base::RefCountedThreadSafe
<PostTaskAndReplyTester
>;
59 ~PostTaskAndReplyTester() {}
62 WaitableEvent test_event_
;
64 // The Impl version performs its checks even in release builds.
65 ThreadCheckerImpl thread_checker_
;
70 TEST_F(WorkerPoolTest
, PostTask
) {
71 WaitableEvent
test_event(false, false);
72 WaitableEvent
long_test_event(false, false);
74 WorkerPool::PostTask(FROM_HERE
,
75 base::Bind(&WaitableEvent::Signal
,
76 base::Unretained(&test_event
)),
78 WorkerPool::PostTask(FROM_HERE
,
79 base::Bind(&WaitableEvent::Signal
,
80 base::Unretained(&long_test_event
)),
84 long_test_event
.Wait();
87 #if defined(OS_WIN) || defined(OS_LINUX)
88 // Flaky on Windows and Linux (http://crbug.com/130337)
89 #define MAYBE_PostTaskAndReply DISABLED_PostTaskAndReply
91 #define MAYBE_PostTaskAndReply PostTaskAndReply
94 TEST_F(WorkerPoolTest
, MAYBE_PostTaskAndReply
) {
95 MessageLoop message_loop
;
96 scoped_refptr
<PostTaskAndReplyTester
> tester(new PostTaskAndReplyTester());
99 const TimeDelta kMaxDuration
= TestTimeouts::tiny_timeout();
100 TimeTicks start
= TimeTicks::Now();
101 while (!tester
->finished() && TimeTicks::Now() - start
< kMaxDuration
) {
103 // Ensure that the other thread has a chance to run even on a single-core
107 RunLoop().RunUntilIdle();
109 EXPECT_TRUE(tester
->finished());