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 Location& from_here, base::OnceClosure task); 42 message_loop()43 base::MessageLoopForIO* message_loop() { 44 return static_cast<base::MessageLoopForIO*>(io_thread_.message_loop()); 45 } 46 task_runner()47 scoped_refptr<SingleThreadTaskRunner> task_runner() { 48 return message_loop()->task_runner(); 49 } 50 51 private: 52 base::Thread io_thread_; 53 bool io_thread_started_; 54 55 DISALLOW_COPY_AND_ASSIGN(TestIOThread); 56 }; 57 58 } // namespace base 59 60 #endif // BASE_TEST_TEST_IO_THREAD_H_ 61