• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 <queue>
10 #include <thread>
11 
12 #include "flutter/fml/closure.h"
13 #include "flutter/fml/macros.h"
14 #include "flutter/fml/synchronization/thread_annotations.h"
15 
16 namespace fml {
17 
18 class ConcurrentTaskRunner;
19 
20 class ConcurrentMessageLoop
21     : public std::enable_shared_from_this<ConcurrentMessageLoop> {
22  public:
23   static std::shared_ptr<ConcurrentMessageLoop> Create(
24       size_t worker_count = std::thread::hardware_concurrency());
25 
26   ~ConcurrentMessageLoop();
27 
28   size_t GetWorkerCount() const;
29 
30   std::shared_ptr<ConcurrentTaskRunner> GetTaskRunner();
31 
32   void Terminate();
33 
34  private:
35   friend ConcurrentTaskRunner;
36 
37   size_t worker_count_ = 0;
38   std::vector<std::thread> workers_;
39   std::mutex tasks_mutex_;
40   std::condition_variable tasks_condition_;
41   std::queue<fml::closure> tasks_;
42   bool shutdown_ = false;
43 
44   ConcurrentMessageLoop(size_t worker_count);
45 
46   void WorkerMain();
47 
48   void PostTask(fml::closure task);
49 
50   FML_DISALLOW_COPY_AND_ASSIGN(ConcurrentMessageLoop);
51 };
52 
53 class ConcurrentTaskRunner {
54  public:
55   ConcurrentTaskRunner(std::weak_ptr<ConcurrentMessageLoop> weak_loop);
56 
57   ~ConcurrentTaskRunner();
58 
59   void PostTask(fml::closure task);
60 
61  private:
62   friend ConcurrentMessageLoop;
63 
64   std::weak_ptr<ConcurrentMessageLoop> weak_loop_;
65 
66   FML_DISALLOW_COPY_AND_ASSIGN(ConcurrentTaskRunner);
67 };
68 
69 }  // namespace fml
70 
71 #endif  // FLUTTER_FML_CONCURRENT_MESSAGE_LOOP_H_
72