Home | History | Annotate | Download | only in test
      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 //
     22 // This API is not thread-safe:
     23 //   - Start()/Stop() should only be called from the main (creation) thread.
     24 //   - PostTask()/message_loop()/task_runner() are also safe to call from the
     25 //     underlying thread itself (to post tasks from other threads: get the
     26 //     task_runner() from the main thread first, it is then safe to pass _it_
     27 //     around).
     28 class TestIOThread {
     29  public:
     30   enum Mode { kAutoStart, kManualStart };
     31   explicit TestIOThread(Mode mode);
     32   // Stops the I/O thread if necessary.
     33   ~TestIOThread();
     34 
     35   // After Stop(), Start() may be called again to start a new I/O thread.
     36   // Stop() may be called even when the I/O thread is not started.
     37   void Start();
     38   void Stop();
     39 
     40   // Post |task| to the IO thread.
     41   void PostTask(const tracked_objects::Location& from_here,
     42                 const base::Closure& task);
     43 
     44   base::MessageLoopForIO* message_loop() {
     45     return static_cast<base::MessageLoopForIO*>(io_thread_.message_loop());
     46   }
     47 
     48   scoped_refptr<SingleThreadTaskRunner> task_runner() {
     49     return message_loop()->task_runner();
     50   }
     51 
     52  private:
     53   base::Thread io_thread_;
     54   bool io_thread_started_;
     55 
     56   DISALLOW_COPY_AND_ASSIGN(TestIOThread);
     57 };
     58 
     59 }  // namespace base
     60 
     61 #endif  // BASE_TEST_TEST_IO_THREAD_H_
     62