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/memory/ref_counted.h"
  9. #include "base/task/task_runner.h"
  10. #include "base/threading/thread.h"
  11. namespace base {
  12. // Create and run an IO thread with a MessageLoop, and
  13. // making the MessageLoop accessible from its client.
  14. // It also provides some ideomatic API like PostTaskAndWait().
  15. //
  16. // This API is not thread-safe:
  17. // - Start()/Stop() should only be called from the main (creation) thread.
  18. // - PostTask()/message_loop()/task_runner() are also safe to call from the
  19. // underlying thread itself (to post tasks from other threads: get the
  20. // task_runner() from the main thread first, it is then safe to pass _it_
  21. // around).
  22. class TestIOThread {
  23. public:
  24. enum Mode { kAutoStart, kManualStart };
  25. explicit TestIOThread(Mode mode);
  26. TestIOThread(const TestIOThread&) = delete;
  27. TestIOThread& operator=(const TestIOThread&) = delete;
  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. };
  43. } // namespace base
  44. #endif // BASE_TEST_TEST_IO_THREAD_H_