| 1 | // Copyright 2013 The Flutter 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 FLUTTER_FML_CONCURRENT_MESSAGE_LOOP_H_ |
| 6 | #define FLUTTER_FML_CONCURRENT_MESSAGE_LOOP_H_ |
| 7 | |
| 8 | #include <condition_variable> |
| 9 | #include <map> |
| 10 | #include <queue> |
| 11 | #include <thread> |
| 12 | |
| 13 | #include "flutter/fml/closure.h" |
| 14 | #include "flutter/fml/macros.h" |
| 15 | #include "flutter/fml/task_runner.h" |
| 16 | |
| 17 | namespace fml { |
| 18 | |
| 19 | class ConcurrentTaskRunner; |
| 20 | |
| 21 | class ConcurrentMessageLoop |
| 22 | : public std::enable_shared_from_this<ConcurrentMessageLoop> { |
| 23 | public: |
| 24 | static std::shared_ptr<ConcurrentMessageLoop> Create( |
| 25 | size_t worker_count = std::thread::hardware_concurrency()); |
| 26 | |
| 27 | virtual ~ConcurrentMessageLoop(); |
| 28 | |
| 29 | size_t GetWorkerCount() const; |
| 30 | |
| 31 | std::shared_ptr<ConcurrentTaskRunner> GetTaskRunner(); |
| 32 | |
| 33 | void Terminate(); |
| 34 | |
| 35 | void PostTaskToAllWorkers(const fml::closure& task); |
| 36 | |
| 37 | bool RunsTasksOnCurrentThread(); |
| 38 | |
| 39 | protected: |
| 40 | explicit ConcurrentMessageLoop(size_t worker_count); |
| 41 | virtual void ExecuteTask(const fml::closure& task); |
| 42 | |
| 43 | private: |
| 44 | friend ConcurrentTaskRunner; |
| 45 | |
| 46 | size_t worker_count_ = 0; |
| 47 | std::vector<std::thread> workers_; |
| 48 | std::mutex tasks_mutex_; |
| 49 | std::condition_variable tasks_condition_; |
| 50 | std::queue<fml::closure> tasks_; |
| 51 | std::vector<std::thread::id> worker_thread_ids_; |
| 52 | std::map<std::thread::id, std::vector<fml::closure>> thread_tasks_; |
| 53 | bool shutdown_ = false; |
| 54 | |
| 55 | void WorkerMain(); |
| 56 | |
| 57 | void PostTask(const fml::closure& task); |
| 58 | |
| 59 | bool HasThreadTasksLocked() const; |
| 60 | |
| 61 | std::vector<fml::closure> GetThreadTasksLocked(); |
| 62 | |
| 63 | FML_DISALLOW_COPY_AND_ASSIGN(ConcurrentMessageLoop); |
| 64 | }; |
| 65 | |
| 66 | class ConcurrentTaskRunner : public BasicTaskRunner { |
| 67 | public: |
| 68 | explicit ConcurrentTaskRunner(std::weak_ptr<ConcurrentMessageLoop> weak_loop); |
| 69 | |
| 70 | virtual ~ConcurrentTaskRunner(); |
| 71 | |
| 72 | void PostTask(const fml::closure& task) override; |
| 73 | |
| 74 | private: |
| 75 | friend ConcurrentMessageLoop; |
| 76 | |
| 77 | std::weak_ptr<ConcurrentMessageLoop> weak_loop_; |
| 78 | |
| 79 | FML_DISALLOW_COPY_AND_ASSIGN(ConcurrentTaskRunner); |
| 80 | }; |
| 81 | |
| 82 | } // namespace fml |
| 83 | |
| 84 | #endif // FLUTTER_FML_CONCURRENT_MESSAGE_LOOP_H_ |
| 85 |
