Flutter Engine
concurrent_message_loop.h
Go to the documentation of this file.
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 
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 
28 
29  size_t GetWorkerCount() const;
30 
31  std::shared_ptr<ConcurrentTaskRunner> GetTaskRunner();
32 
33  void Terminate();
34 
36 
37  private:
38  friend ConcurrentTaskRunner;
39 
40  size_t worker_count_ = 0;
41  std::vector<std::thread> workers_;
42  std::mutex tasks_mutex_;
43  std::condition_variable tasks_condition_;
44  std::queue<fml::closure> tasks_;
45  std::vector<std::thread::id> worker_thread_ids_;
46  std::map<std::thread::id, std::vector<fml::closure>> thread_tasks_;
47  bool shutdown_ = false;
48 
49  ConcurrentMessageLoop(size_t worker_count);
50 
51  void WorkerMain();
52 
53  void PostTask(const fml::closure& task);
54 
55  bool HasThreadTasksLocked() const;
56 
57  std::vector<fml::closure> GetThreadTasksLocked();
58 
59  FML_DISALLOW_COPY_AND_ASSIGN(ConcurrentMessageLoop);
60 };
61 
63  public:
64  ConcurrentTaskRunner(std::weak_ptr<ConcurrentMessageLoop> weak_loop);
65 
66  virtual ~ConcurrentTaskRunner();
67 
68  void PostTask(const fml::closure& task) override;
69 
70  private:
71  friend ConcurrentMessageLoop;
72 
73  std::weak_ptr<ConcurrentMessageLoop> weak_loop_;
74 
76 };
77 
78 } // namespace fml
79 
80 #endif // FLUTTER_FML_CONCURRENT_MESSAGE_LOOP_H_
std::shared_ptr< ConcurrentTaskRunner > GetTaskRunner()
Definition: ascii_trie.cc:9
void PostTaskToAllWorkers(fml::closure task)
std::function< void()> closure
Definition: closure.h:14
static std::shared_ptr< ConcurrentMessageLoop > Create(size_t worker_count=std::thread::hardware_concurrency())
An interface over the ability to schedule tasks on a TaskRunner.
Definition: task_runner.h:20
#define FML_DISALLOW_COPY_AND_ASSIGN(TypeName)
Definition: macros.h:27