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