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/thread.h"
10 #include "base/location.h"
11 #include "base/single_thread_task_runner.h"
12 #include "base/synchronization/waitable_event.h"
13 #include "base/third_party/dynamic_annotations/dynamic_annotations.h"
14 #include "testing/gtest/include/gtest/gtest.h"
15 #include "testing/platform_test.h"
19 typedef PlatformTest ThreadTest
;
23 void ToggleValue(bool* value
) {
24 ANNOTATE_BENIGN_RACE(value
, "Test-only data race on boolean "
25 "in base/thread_unittest");
29 class SleepInsideInitThread
: public Thread
{
31 SleepInsideInitThread() : Thread("none") {
34 this, "Benign test-only data race on vptr - http://crbug.com/98219");
36 ~SleepInsideInitThread() override
{ Stop(); }
38 void Init() override
{
39 base::PlatformThread::Sleep(base::TimeDelta::FromMilliseconds(500));
42 bool InitCalled() { return init_called_
; }
48 // Thread::Init() was called.
49 THREAD_EVENT_INIT
= 0,
51 // The MessageLoop for the thread was deleted.
52 THREAD_EVENT_MESSAGE_LOOP_DESTROYED
,
54 // Thread::CleanUp() was called.
57 // Keep at end of list.
61 typedef std::vector
<ThreadEvent
> EventList
;
63 class CaptureToEventList
: public Thread
{
65 // This Thread pushes events into the vector |event_list| to show
66 // the order they occured in. |event_list| must remain valid for the
67 // lifetime of this thread.
68 explicit CaptureToEventList(EventList
* event_list
)
70 event_list_(event_list
) {
73 ~CaptureToEventList() override
{ Stop(); }
75 void Init() override
{ event_list_
->push_back(THREAD_EVENT_INIT
); }
77 void CleanUp() override
{ event_list_
->push_back(THREAD_EVENT_CLEANUP
); }
80 EventList
* event_list_
;
83 // Observer that writes a value into |event_list| when a message loop has been
85 class CapturingDestructionObserver
86 : public base::MessageLoop::DestructionObserver
{
88 // |event_list| must remain valid throughout the observer's lifetime.
89 explicit CapturingDestructionObserver(EventList
* event_list
)
90 : event_list_(event_list
) {
93 // DestructionObserver implementation:
94 void WillDestroyCurrentMessageLoop() override
{
95 event_list_
->push_back(THREAD_EVENT_MESSAGE_LOOP_DESTROYED
);
100 EventList
* event_list_
;
103 // Task that adds a destruction observer to the current message loop.
104 void RegisterDestructionObserver(
105 base::MessageLoop::DestructionObserver
* observer
) {
106 base::MessageLoop::current()->AddDestructionObserver(observer
);
109 // Task that calls GetThreadId() of |thread|, stores the result into |id|, then
111 void ReturnThreadId(base::Thread
* thread
,
112 base::PlatformThreadId
* id
,
113 base::WaitableEvent
* event
) {
114 *id
= thread
->GetThreadId();
120 TEST_F(ThreadTest
, Restart
) {
123 EXPECT_FALSE(a
.message_loop());
124 EXPECT_FALSE(a
.IsRunning());
125 EXPECT_TRUE(a
.Start());
126 EXPECT_TRUE(a
.message_loop());
127 EXPECT_TRUE(a
.IsRunning());
129 EXPECT_FALSE(a
.message_loop());
130 EXPECT_FALSE(a
.IsRunning());
131 EXPECT_TRUE(a
.Start());
132 EXPECT_TRUE(a
.message_loop());
133 EXPECT_TRUE(a
.IsRunning());
135 EXPECT_FALSE(a
.message_loop());
136 EXPECT_FALSE(a
.IsRunning());
138 EXPECT_FALSE(a
.message_loop());
139 EXPECT_FALSE(a
.IsRunning());
142 TEST_F(ThreadTest
, StartWithOptions_StackSize
) {
143 Thread
a("StartWithStackSize");
144 // Ensure that the thread can work with only 12 kb and still process a
146 Thread::Options options
;
147 #if defined(ADDRESS_SANITIZER) && defined(OS_MACOSX)
148 // ASan bloats the stack variables and overflows the 12 kb stack on OSX.
149 options
.stack_size
= 24*1024;
151 options
.stack_size
= 12*1024;
153 EXPECT_TRUE(a
.StartWithOptions(options
));
154 EXPECT_TRUE(a
.message_loop());
155 EXPECT_TRUE(a
.IsRunning());
157 bool was_invoked
= false;
158 a
.task_runner()->PostTask(FROM_HERE
, base::Bind(&ToggleValue
, &was_invoked
));
160 // wait for the task to run (we could use a kernel event here
161 // instead to avoid busy waiting, but this is sufficient for
162 // testing purposes).
163 for (int i
= 100; i
>= 0 && !was_invoked
; --i
) {
164 base::PlatformThread::Sleep(base::TimeDelta::FromMilliseconds(10));
166 EXPECT_TRUE(was_invoked
);
169 TEST_F(ThreadTest
, TwoTasks
) {
170 bool was_invoked
= false;
172 Thread
a("TwoTasks");
173 EXPECT_TRUE(a
.Start());
174 EXPECT_TRUE(a
.message_loop());
176 // Test that all events are dispatched before the Thread object is
177 // destroyed. We do this by dispatching a sleep event before the
178 // event that will toggle our sentinel value.
179 a
.task_runner()->PostTask(
180 FROM_HERE
, base::Bind(static_cast<void (*)(base::TimeDelta
)>(
181 &base::PlatformThread::Sleep
),
182 base::TimeDelta::FromMilliseconds(20)));
183 a
.task_runner()->PostTask(FROM_HERE
,
184 base::Bind(&ToggleValue
, &was_invoked
));
186 EXPECT_TRUE(was_invoked
);
189 TEST_F(ThreadTest
, StopSoon
) {
190 Thread
a("StopSoon");
191 EXPECT_TRUE(a
.Start());
192 EXPECT_TRUE(a
.message_loop());
193 EXPECT_TRUE(a
.IsRunning());
197 EXPECT_FALSE(a
.message_loop());
198 EXPECT_FALSE(a
.IsRunning());
201 TEST_F(ThreadTest
, ThreadName
) {
202 Thread
a("ThreadName");
203 EXPECT_TRUE(a
.Start());
204 EXPECT_EQ("ThreadName", a
.thread_name());
207 TEST_F(ThreadTest
, ThreadId
) {
208 Thread
a("ThreadId0");
209 Thread
b("ThreadId1");
213 // Post a task that calls GetThreadId() on the created thread.
214 base::WaitableEvent
event(false, false);
215 base::PlatformThreadId id_from_new_thread
;
216 a
.task_runner()->PostTask(
217 FROM_HERE
, base::Bind(ReturnThreadId
, &a
, &id_from_new_thread
, &event
));
219 // Call GetThreadId() on the current thread before calling event.Wait() so
220 // that this test can find a race issue with TSAN.
221 base::PlatformThreadId id_from_current_thread
= a
.GetThreadId();
223 // Check if GetThreadId() returns consistent value in both threads.
225 EXPECT_EQ(id_from_current_thread
, id_from_new_thread
);
227 // A started thread should have a valid ID.
228 EXPECT_NE(base::kInvalidThreadId
, a
.GetThreadId());
229 EXPECT_NE(base::kInvalidThreadId
, b
.GetThreadId());
231 // Each thread should have a different thread ID.
232 EXPECT_NE(a
.GetThreadId(), b
.GetThreadId());
235 TEST_F(ThreadTest
, ThreadIdWithRestart
) {
236 Thread
a("ThreadIdWithRestart");
237 base::PlatformThreadId previous_id
= base::kInvalidThreadId
;
239 for (size_t i
= 0; i
< 16; ++i
) {
240 EXPECT_TRUE(a
.Start());
241 base::PlatformThreadId current_id
= a
.GetThreadId();
242 EXPECT_NE(previous_id
, current_id
);
243 previous_id
= current_id
;
248 // Make sure Init() is called after Start() and before
249 // WaitUntilThreadInitialized() returns.
250 TEST_F(ThreadTest
, SleepInsideInit
) {
251 SleepInsideInitThread t
;
252 EXPECT_FALSE(t
.InitCalled());
253 t
.StartAndWaitForTesting();
254 EXPECT_TRUE(t
.InitCalled());
257 // Make sure that the destruction sequence is:
259 // (1) Thread::CleanUp()
260 // (2) MessageLoop::~MessageLoop()
261 // MessageLoop::DestructionObservers called.
262 TEST_F(ThreadTest
, CleanUp
) {
263 EventList captured_events
;
264 CapturingDestructionObserver
loop_destruction_observer(&captured_events
);
267 // Start a thread which writes its event into |captured_events|.
268 CaptureToEventList
t(&captured_events
);
269 EXPECT_TRUE(t
.Start());
270 EXPECT_TRUE(t
.message_loop());
271 EXPECT_TRUE(t
.IsRunning());
273 // Register an observer that writes into |captured_events| once the
274 // thread's message loop is destroyed.
275 t
.task_runner()->PostTask(
276 FROM_HERE
, base::Bind(&RegisterDestructionObserver
,
277 base::Unretained(&loop_destruction_observer
)));
279 // Upon leaving this scope, the thread is deleted.
282 // Check the order of events during shutdown.
283 ASSERT_EQ(static_cast<size_t>(THREAD_NUM_EVENTS
), captured_events
.size());
284 EXPECT_EQ(THREAD_EVENT_INIT
, captured_events
[0]);
285 EXPECT_EQ(THREAD_EVENT_CLEANUP
, captured_events
[1]);
286 EXPECT_EQ(THREAD_EVENT_MESSAGE_LOOP_DESTROYED
, captured_events
[2]);
289 TEST_F(ThreadTest
, ThreadNotStarted
) {
291 EXPECT_EQ(nullptr, a
.task_runner());