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 namespace bluetooth {
28 namespace os {
29 
30 namespace {
31 constexpr int kRealTimeFifoSchedulingPriority = 1;
32 }
33 
Thread(const std::string & name,const Priority priority)34 Thread::Thread(const std::string& name, const Priority priority)
35     : name_(name), reactor_(), running_thread_(&Thread::run, this, priority) {}
36 
run(Priority priority)37 void Thread::run(Priority priority) {
38   if (priority == Priority::REAL_TIME) {
39     struct sched_param rt_params = {.sched_priority = kRealTimeFifoSchedulingPriority};
40     auto linux_tid = static_cast<pid_t>(syscall(SYS_gettid));
41     int rc;
42     RUN_NO_INTR(rc = sched_setscheduler(linux_tid, SCHED_FIFO, &rt_params));
43     if (rc != 0) {
44       log::error("unable to set SCHED_FIFO priority: {}", strerror(errno));
45     }
46   }
47   reactor_.Run();
48 }
49 
~Thread()50 Thread::~Thread() { Stop(); }
51 
Stop()52 bool Thread::Stop() {
53   std::lock_guard<std::mutex> lock(mutex_);
54   log::assert_that(std::this_thread::get_id() != running_thread_.get_id(),
55                    "assert failed: std::this_thread::get_id() != running_thread_.get_id()");
56 
57   if (!running_thread_.joinable()) {
58     return false;
59   }
60   reactor_.Stop();
61   running_thread_.join();
62   return true;
63 }
64 
IsSameThread() const65 bool Thread::IsSameThread() const { return std::this_thread::get_id() == running_thread_.get_id(); }
66 
GetReactor() const67 Reactor* Thread::GetReactor() const { return &reactor_; }
68 
GetThreadName() const69 std::string Thread::GetThreadName() const { return name_; }
70 
ToString() const71 std::string Thread::ToString() const { return "Thread " + name_; }
72 
73 }  // namespace os
74 }  // namespace bluetooth
75