Flutter Engine
thread.cc
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 #include "thread.h"
6 
7 #include <lib/async-loop/cpp/loop.h>
8 #include <unistd.h>
9 
10 #include <algorithm>
11 #include <climits>
12 
13 #include "flutter/fml/logging.h"
14 #include "loop.h"
15 
16 namespace flutter_runner {
17 
18 typedef void (*ThreadEntry)(Thread*);
19 
20 namespace {
21 
22 size_t NextPageSizeMultiple(size_t size) {
23  const size_t page_size = sysconf(_SC_PAGE_SIZE);
24  FML_CHECK(page_size != 0);
25 
26  size = std::max<size_t>(size, page_size);
27 
28  size_t rem = size % page_size;
29 
30  if (rem == 0) {
31  return size;
32  }
33 
34  return size + page_size - rem;
35 }
36 
37 bool CreateThread(pthread_t* thread,
39  Thread* argument,
40  size_t stack_size) {
41  pthread_attr_t thread_attributes;
42 
43  if (pthread_attr_init(&thread_attributes) != 0) {
44  return false;
45  }
46 
47  stack_size = std::max<size_t>(NextPageSizeMultiple(PTHREAD_STACK_MIN),
48  NextPageSizeMultiple(stack_size));
49 
50  if (pthread_attr_setstacksize(&thread_attributes, stack_size) != 0) {
51  return false;
52  }
53 
54  auto result =
55  pthread_create(thread, &thread_attributes,
56  reinterpret_cast<void* (*)(void*)>(main), argument);
57 
58  pthread_attr_destroy(&thread_attributes);
59 
60  return result == 0;
61 }
62 
63 } // anonymous namespace
64 
66  loop_.reset(MakeObservableLoop(false));
67  valid_ = CreateThread(
68  &thread_, [](Thread* thread) { thread->Main(); }, this, 1 << 20);
69 }
70 
72  Join();
73 }
74 
75 bool Thread::IsValid() const {
76  return valid_;
77 }
78 
79 async_dispatcher_t* Thread::dispatcher() const {
80  return loop_->dispatcher();
81 }
82 
83 void Thread::Main() {
84  async_set_default_dispatcher(loop_->dispatcher());
85  loop_->Run();
86 }
87 
88 void Thread::Quit() {
89  loop_->Quit();
90 }
91 
92 bool Thread::Join() {
93  if (!valid_) {
94  return false;
95  }
96 
97  bool result = pthread_join(thread_, nullptr) == 0;
98  valid_ = false;
99  return result;
100 }
101 
102 } // namespace flutter_runner
bool IsValid() const
Definition: thread.cc:75
int main(int argc, char **argv)
Definition: benchmarking.cc:22
constexpr std::size_t size(T(&array)[N])
Definition: size.h:13
async::Loop * MakeObservableLoop(bool attachToThread)
Definition: loop.cc:42
#define FML_CHECK(condition)
Definition: logging.h:68
async_dispatcher_t * dispatcher() const
Definition: thread.cc:79
void(* ThreadEntry)(Thread *)
Definition: thread.cc:18