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, and stops after
30 // Stop() is invoked. To assign task to this thread, user needs to register a reactable object to the underlying
31 // reactor.
32 class Thread {
33  public:
34   // Used by thread constructor. Suggest the priority to the kernel scheduler. Use REAL_TIME if we need (soft) real-time
35   // scheduling guarantee for this thread; use NORMAL if no real-time guarantee is needed to save CPU time slice for
36   // 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 be started again.
53   bool Stop();
54 
55   // Return true if this function is invoked from this thread
56   bool IsSameThread() const;
57 
58   // Return the POSIX thread name
59   std::string GetThreadName() const;
60 
61   // Return a user-friendly string representation of this thread object
62   std::string ToString() const;
63 
64   // Return the pointer of underlying reactor. The ownership is NOT transferred.
65   Reactor* GetReactor() const;
66 
67  private:
68   void run(Priority priority);
69   mutable std::mutex mutex_;
70   const std::string name_;
71   mutable Reactor reactor_;
72   std::thread running_thread_;
73 };
74 
75 }  // namespace os
76 }  // namespace bluetooth
77