• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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   // Stop and destroy this thread
47   ~Thread();
48 
49   DISALLOW_COPY_AND_ASSIGN(Thread);
50 
51   // Stop this thread. Must be invoked from another thread. After this thread is stopped, it cannot be started again.
52   bool Stop();
53 
54   // Return true if this function is invoked from this thread
55   bool IsSameThread() const;
56 
57   // Return the POSIX thread name
58   std::string GetThreadName() const;
59 
60   // Return a user-friendly string representation of this thread object
61   std::string ToString() const;
62 
63   // Return the pointer of underlying reactor. The ownership is NOT transferred.
64   Reactor* GetReactor() const;
65 
66  private:
67   void run(Priority priority);
68   mutable std::mutex mutex_;
69   const std::string name_;
70   mutable Reactor reactor_;
71   std::thread running_thread_;
72 };
73 
74 }  // namespace os
75 }  // namespace bluetooth
76