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 #pragma once
18 
19 #include <mutex>
20 #include <string>
21 #include <thread>
22 
23 #include "os/reactor.h"
24 #include "os/utils.h"
25 
26 namespace bluetooth {
27 namespace os {
28 
29 // Reactor-based looper thread implementation. The thread runs immediately after it is constructed,
30 // and stops after Stop() is invoked. To assign task to this thread, user needs to register a
31 // reactable object to the underlying reactor.
32 class Thread {
33 public:
34   // Used by thread constructor. Suggest the priority to the kernel scheduler. Use REAL_TIME if we
35   // need (soft) real-time scheduling guarantee for this thread; use NORMAL if no real-time
36   // guarantee is needed to save CPU time slice for other threads
37   enum class Priority {
38     REAL_TIME,
39     NORMAL,
40   };
41 
42   // name: thread name for POSIX systems
43   // priority: priority for kernel scheduler
44   Thread(const std::string& name, Priority priority);
45 
46   Thread(const Thread&) = delete;
47   Thread& operator=(const Thread&) = delete;
48 
49   // Stop and destroy this thread
50   ~Thread();
51 
52   // Stop this thread. Must be invoked from another thread. After this thread is stopped, it cannot
53   // be started again.
54   bool Stop();
55 
56   // Return true if this function is invoked from this thread
57   bool IsSameThread() const;
58 
59   // Return the POSIX thread name
60   std::string GetThreadName() const;
61 
62   // Return a user-friendly string representation of this thread object
63   std::string ToString() const;
64 
65   // Return the pointer of underlying reactor. The ownership is NOT transferred.
66   Reactor* GetReactor() const;
67 
68 private:
69   void run(Priority priority);
70   mutable std::mutex mutex_;
71   const std::string name_;
72   mutable Reactor reactor_;
73   std::thread running_thread_;
74 };
75 
76 }  // namespace os
77 }  // namespace bluetooth
78