1 /*
2  * Copyright 2019 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #include "os/thread.h"
18 
19 #include <bluetooth/log.h>
20 #include <fcntl.h>
21 #include <sys/syscall.h>
22 #include <unistd.h>
23 
24 #include <cerrno>
25 #include <cstring>
26 
27 #include "os/log.h"
28 
29 namespace bluetooth {
30 namespace os {
31 
32 namespace {
33 constexpr int kRealTimeFifoSchedulingPriority = 1;
34 }
35 
Thread(const std::string & name,const Priority priority)36 Thread::Thread(const std::string& name, const Priority priority)
37     : name_(name), reactor_(), running_thread_(&Thread::run, this, priority) {}
38 
run(Priority priority)39 void Thread::run(Priority priority) {
40   if (priority == Priority::REAL_TIME) {
41     struct sched_param rt_params = {.sched_priority = kRealTimeFifoSchedulingPriority};
42     auto linux_tid = static_cast<pid_t>(syscall(SYS_gettid));
43     int rc;
44     RUN_NO_INTR(rc = sched_setscheduler(linux_tid, SCHED_FIFO, &rt_params));
45     if (rc != 0) {
46       log::error("unable to set SCHED_FIFO priority: {}", strerror(errno));
47     }
48   }
49   reactor_.Run();
50 }
51 
~Thread()52 Thread::~Thread() {
53   Stop();
54 }
55 
Stop()56 bool Thread::Stop() {
57   std::lock_guard<std::mutex> lock(mutex_);
58   log::assert_that(
59       std::this_thread::get_id() != running_thread_.get_id(),
60       "assert failed: std::this_thread::get_id() != running_thread_.get_id()");
61 
62   if (!running_thread_.joinable()) {
63     return false;
64   }
65   reactor_.Stop();
66   running_thread_.join();
67   return true;
68 }
69 
IsSameThread() const70 bool Thread::IsSameThread() const {
71   return std::this_thread::get_id() == running_thread_.get_id();
72 }
73 
GetReactor() const74 Reactor* Thread::GetReactor() const {
75   return &reactor_;
76 }
77 
GetThreadName() const78 std::string Thread::GetThreadName() const {
79   return name_;
80 }
81 
ToString() const82 std::string Thread::ToString() const {
83   return "Thread " + name_;
84 }
85 
86 }  // namespace os
87 }  // namespace bluetooth
88