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 <unistd.h>
21 #include <sys/syscall.h>
22 #include <cerrno>
23 #include <cstring>
24
25 #include "os/log.h"
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),
36 reactor_(),
37 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: %s", 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 ASSERT(std::this_thread::get_id() != running_thread_.get_id());
59
60 if (!running_thread_.joinable()) {
61 return false;
62 }
63 reactor_.Stop();
64 running_thread_.join();
65 return true;
66 }
67
IsSameThread() const68 bool Thread::IsSameThread() const {
69 return std::this_thread::get_id() == running_thread_.get_id();
70 }
71
GetReactor() const72 Reactor* Thread::GetReactor() const {
73 return &reactor_;
74 }
75
GetThreadName() const76 std::string Thread::GetThreadName() const {
77 return name_;
78 }
79
ToString() const80 std::string Thread::ToString() const {
81 return "Thread " + name_;
82 }
83
84 } // namespace os
85 } // namespace bluetooth
86