16d528ed9Sopenharmony_ci// Copyright 2018 The Chromium Authors. All rights reserved. 26d528ed9Sopenharmony_ci// Use of this source code is governed by a BSD-style license that can be 36d528ed9Sopenharmony_ci// found in the LICENSE file. 46d528ed9Sopenharmony_ci 56d528ed9Sopenharmony_ci#ifndef UTIL_RUN_LOOP_H_ 66d528ed9Sopenharmony_ci#define UTIL_RUN_LOOP_H_ 76d528ed9Sopenharmony_ci 86d528ed9Sopenharmony_ci#include <condition_variable> 96d528ed9Sopenharmony_ci#include <functional> 106d528ed9Sopenharmony_ci#include <mutex> 116d528ed9Sopenharmony_ci#include <queue> 126d528ed9Sopenharmony_ci 136d528ed9Sopenharmony_ciclass MsgLoop { 146d528ed9Sopenharmony_ci public: 156d528ed9Sopenharmony_ci MsgLoop(); 166d528ed9Sopenharmony_ci ~MsgLoop(); 176d528ed9Sopenharmony_ci 186d528ed9Sopenharmony_ci // Blocks until PostQuit() is called, processing work items posted via 196d528ed9Sopenharmony_ci void Run(); 206d528ed9Sopenharmony_ci 216d528ed9Sopenharmony_ci // Schedules Run() to exit, but will not happen until other outstanding tasks 226d528ed9Sopenharmony_ci // complete. Can be called from any thread. 236d528ed9Sopenharmony_ci void PostQuit(); 246d528ed9Sopenharmony_ci 256d528ed9Sopenharmony_ci // Posts a work item to this queue. All items will be run on the thread from 266d528ed9Sopenharmony_ci // which Run() was called. Can be called from any thread. 276d528ed9Sopenharmony_ci void PostTask(std::function<void()> task); 286d528ed9Sopenharmony_ci 296d528ed9Sopenharmony_ci // Run()s until the queue is empty. Should only be used (carefully) in tests. 306d528ed9Sopenharmony_ci void RunUntilIdleForTesting(); 316d528ed9Sopenharmony_ci 326d528ed9Sopenharmony_ci // Gets the MsgLoop for the thread from which it's called, or nullptr if 336d528ed9Sopenharmony_ci // there's no MsgLoop for the current thread. 346d528ed9Sopenharmony_ci static MsgLoop* Current(); 356d528ed9Sopenharmony_ci 366d528ed9Sopenharmony_ci private: 376d528ed9Sopenharmony_ci std::mutex queue_mutex_; 386d528ed9Sopenharmony_ci std::queue<std::function<void()>> task_queue_; 396d528ed9Sopenharmony_ci std::condition_variable notifier_; 406d528ed9Sopenharmony_ci bool should_quit_ = false; 416d528ed9Sopenharmony_ci 426d528ed9Sopenharmony_ci MsgLoop(const MsgLoop&) = delete; 436d528ed9Sopenharmony_ci MsgLoop& operator=(const MsgLoop&) = delete; 446d528ed9Sopenharmony_ci}; 456d528ed9Sopenharmony_ci 466d528ed9Sopenharmony_ci#endif // UTIL_RUN_LOOP_H_ 47