run_loop.h 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. /*
  2. * Copyright (c) 2013 The WebRTC project authors. All Rights Reserved.
  3. *
  4. * Use of this source code is governed by a BSD-style license
  5. * that can be found in the LICENSE file in the root of the source
  6. * tree. An additional intellectual property rights grant can be found
  7. * in the file PATENTS. All contributing project authors may
  8. * be found in the AUTHORS file in the root of the source tree.
  9. */
  10. #ifndef TEST_RUN_LOOP_H_
  11. #define TEST_RUN_LOOP_H_
  12. #include "rtc_base/task_utils/to_queued_task.h"
  13. #include "rtc_base/thread.h"
  14. namespace webrtc {
  15. namespace test {
  16. // This utility class allows you to run a TaskQueue supported interface on the
  17. // main test thread, call Run() while doing things asynchonously and break
  18. // the loop (from the same thread) from a callback by calling Quit().
  19. class RunLoop {
  20. public:
  21. RunLoop();
  22. ~RunLoop();
  23. TaskQueueBase* task_queue();
  24. void Run();
  25. void Quit();
  26. void Flush();
  27. // Convenience methods since TaskQueueBase doesn't support this sort of magic.
  28. template <typename Closure>
  29. void PostTask(Closure&& task) {
  30. task_queue()->PostTask(ToQueuedTask(std::forward<Closure>(task)));
  31. }
  32. template <typename Closure>
  33. void PostDelayedTask(Closure&& task, uint32_t milliseconds) {
  34. task_queue()->PostDelayedTask(ToQueuedTask(std::forward<Closure>(task)),
  35. milliseconds);
  36. }
  37. private:
  38. class FakeSocketServer : public rtc::SocketServer {
  39. public:
  40. FakeSocketServer();
  41. ~FakeSocketServer();
  42. void FailNextWait();
  43. private:
  44. bool Wait(int cms, bool process_io) override;
  45. void WakeUp() override;
  46. rtc::Socket* CreateSocket(int family, int type) override;
  47. rtc::AsyncSocket* CreateAsyncSocket(int family, int type) override;
  48. private:
  49. bool fail_next_wait_ = false;
  50. };
  51. class WorkerThread : public rtc::Thread {
  52. public:
  53. explicit WorkerThread(rtc::SocketServer* ss);
  54. private:
  55. CurrentTaskQueueSetter tq_setter_;
  56. };
  57. FakeSocketServer socket_server_;
  58. WorkerThread worker_thread_{&socket_server_};
  59. };
  60. } // namespace test
  61. } // namespace webrtc
  62. #endif // TEST_RUN_LOOP_H_