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.
4 
5 #ifndef BASE_TEST_TEST_IO_THREAD_H_
6 #define BASE_TEST_TEST_IO_THREAD_H_
7 
8 #include "base/callback_forward.h"
9 #include "base/compiler_specific.h"
10 #include "base/macros.h"
11 #include "base/memory/ref_counted.h"
12 #include "base/task_runner.h"
13 #include "base/threading/thread.h"
14 #include "base/time/time.h"
15 
16 namespace base {
17 
18 // Create and run an IO thread with a MessageLoop, and
19 // making the MessageLoop accessible from its client.
20 // It also provides some ideomatic API like PostTaskAndWait().
21 class TestIOThread {
22  public:
23   enum Mode { kAutoStart, kManualStart };
24   explicit TestIOThread(Mode mode);
25   // Stops the I/O thread if necessary.
26   ~TestIOThread();
27 
28   // |Start()|/|Stop()| should only be called from the main (creation) thread.
29   // After |Stop()|, |Start()| may be called again to start a new I/O thread.
30   // |Stop()| may be called even when the I/O thread is not started.
31   void Start();
32   void Stop();
33 
34   // Post |task| to the IO thread.
35   void PostTask(const tracked_objects::Location& from_here,
36                 const base::Closure& task);
37   // Posts |task| to the IO-thread with an WaitableEvent associated blocks on
38   // it until the posted |task| is executed, then returns.
39   void PostTaskAndWait(const tracked_objects::Location& from_here,
40                        const base::Closure& task);
41 
message_loop()42   base::MessageLoopForIO* message_loop() {
43     return static_cast<base::MessageLoopForIO*>(io_thread_.message_loop());
44   }
45 
task_runner()46   scoped_refptr<SingleThreadTaskRunner> task_runner() {
47     return message_loop()->task_runner();
48   }
49 
50  private:
51   base::Thread io_thread_;
52   bool io_thread_started_;
53 
54   DISALLOW_COPY_AND_ASSIGN(TestIOThread);
55 };
56 
57 }  // namespace base
58 
59 #endif  // BASE_TEST_TEST_IO_THREAD_H_
60