• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2018 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 UTIL_RUN_LOOP_H_
6 #define UTIL_RUN_LOOP_H_
7 
8 #include <condition_variable>
9 #include <functional>
10 #include <mutex>
11 #include <queue>
12 
13 class MsgLoop {
14  public:
15   MsgLoop();
16   ~MsgLoop();
17 
18   // Blocks until PostQuit() is called, processing work items posted via
19   void Run();
20 
21   // Schedules Run() to exit, but will not happen until other outstanding tasks
22   // complete. Can be called from any thread.
23   void PostQuit();
24 
25   // Posts a work item to this queue. All items will be run on the thread from
26   // which Run() was called. Can be called from any thread.
27   void PostTask(std::function<void()> task);
28 
29   // Run()s until the queue is empty. Should only be used (carefully) in tests.
30   void RunUntilIdleForTesting();
31 
32   // Gets the MsgLoop for the thread from which it's called, or nullptr if
33   // there's no MsgLoop for the current thread.
34   static MsgLoop* Current();
35 
36  private:
37   std::mutex queue_mutex_;
38   std::queue<std::function<void()>> task_queue_;
39   std::condition_variable notifier_;
40   bool should_quit_ = false;
41 
42   MsgLoop(const MsgLoop&) = delete;
43   MsgLoop& operator=(const MsgLoop&) = delete;
44 };
45 
46 #endif  // UTIL_RUN_LOOP_H_
47