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 <fcntl.h>
20 #include <sys/syscall.h>
21 #include <unistd.h>
22 
23 #include <cerrno>
24 #include <cstring>
25 
26 #include "os/log.h"
27 
28 namespace bluetooth {
29 namespace os {
30 
31 namespace {
32 constexpr int kRealTimeFifoSchedulingPriority = 1;
33 }
34 
Thread(const std::string & name,const Priority priority)35 Thread::Thread(const std::string& name, const Priority priority)
36     : name_(name), reactor_(), running_thread_(&Thread::run, this, priority) {}
37 
run(Priority priority)38 void Thread::run(Priority priority) {
39   if (priority == Priority::REAL_TIME) {
40     struct sched_param rt_params = {.sched_priority = kRealTimeFifoSchedulingPriority};
41     auto linux_tid = static_cast<pid_t>(syscall(SYS_gettid));
42     int rc;
43     RUN_NO_INTR(rc = sched_setscheduler(linux_tid, SCHED_FIFO, &rt_params));
44     if (rc != 0) {
45       LOG_ERROR("unable to set SCHED_FIFO priority: %s", strerror(errno));
46     }
47   }
48   reactor_.Run();
49 }
50 
~Thread()51 Thread::~Thread() {
52   Stop();
53 }
54 
Stop()55 bool Thread::Stop() {
56   std::lock_guard<std::mutex> lock(mutex_);
57   ASSERT(std::this_thread::get_id() != running_thread_.get_id());
58 
59   if (!running_thread_.joinable()) {
60     return false;
61   }
62   reactor_.Stop();
63   running_thread_.join();
64   return true;
65 }
66 
IsSameThread() const67 bool Thread::IsSameThread() const {
68   return std::this_thread::get_id() == running_thread_.get_id();
69 }
70 
GetReactor() const71 Reactor* Thread::GetReactor() const {
72   return &reactor_;
73 }
74 
GetThreadName() const75 std::string Thread::GetThreadName() const {
76   return name_;
77 }
78 
ToString() const79 std::string Thread::ToString() const {
80   return "Thread " + name_;
81 }
82 
83 }  // namespace os
84 }  // namespace bluetooth
85