test_io_thread.h 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  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. #ifndef BASE_TEST_TEST_IO_THREAD_H_
  5. #define BASE_TEST_TEST_IO_THREAD_H_
  6. #include "base/callback_forward.h"
  7. #include "base/compiler_specific.h"
  8. #include "base/macros.h"
  9. #include "base/memory/ref_counted.h"
  10. #include "base/task_runner.h"
  11. #include "base/threading/thread.h"
  12. #include "base/time/time.h"
  13. namespace base {
  14. // Create and run an IO thread with a MessageLoop, and
  15. // making the MessageLoop accessible from its client.
  16. // It also provides some ideomatic API like PostTaskAndWait().
  17. //
  18. // This API is not thread-safe:
  19. // - Start()/Stop() should only be called from the main (creation) thread.
  20. // - PostTask()/message_loop()/task_runner() are also safe to call from the
  21. // underlying thread itself (to post tasks from other threads: get the
  22. // task_runner() from the main thread first, it is then safe to pass _it_
  23. // around).
  24. class TestIOThread {
  25. public:
  26. enum Mode { kAutoStart, kManualStart };
  27. explicit TestIOThread(Mode mode);
  28. // Stops the I/O thread if necessary.
  29. ~TestIOThread();
  30. // After Stop(), Start() may be called again to start a new I/O thread.
  31. // Stop() may be called even when the I/O thread is not started.
  32. void Start();
  33. void Stop();
  34. // Post |task| to the IO thread.
  35. void PostTask(const Location& from_here, base::OnceClosure task);
  36. scoped_refptr<SingleThreadTaskRunner> task_runner() {
  37. return io_thread_.task_runner();
  38. }
  39. private:
  40. base::Thread io_thread_;
  41. bool io_thread_started_;
  42. DISALLOW_COPY_AND_ASSIGN(TestIOThread);
  43. };
  44. } // namespace base
  45. #endif // BASE_TEST_TEST_IO_THREAD_H_