• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2015-2016 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 #ifndef ANDROID_WORKER_H_
18 #define ANDROID_WORKER_H_
19 
20 #include <android-base/thread_annotations.h>
21 #include <stdint.h>
22 #include <stdlib.h>
23 #include <string>
24 
25 #include <condition_variable>
26 #include <mutex>
27 #include <thread>
28 
29 namespace android {
30 
31 class Worker {
32  public:
Lock()33   void Lock() ACQUIRE(mutex_) {
34     mutex_.lock();
35   }
Unlock()36   void Unlock() RELEASE(mutex_) {
37     mutex_.unlock();
38   }
39 
Signal()40   void Signal() {
41     cond_.notify_all();
42   }
43   void Exit();
44 
initialized()45   bool initialized() const {
46     return initialized_;
47   }
48 
49   int InitWorker();
50 
51  protected:
52   Worker(const char *name, int priority, bool is_rt = false);
53   virtual ~Worker();
54 
55   virtual void Routine() = 0;
56 
57   /*
58    * Must be called with the lock acquired. max_nanoseconds may be negative to
59    * indicate infinite timeout, otherwise it indicates the maximum time span to
60    * wait for a signal before returning.
61    * Returns -EINTR if interrupted by exit request, or -ETIMEDOUT if timed out
62    */
63   int WaitForSignalOrExitLocked(int64_t max_nanoseconds = -1);
64 
should_exit()65   bool should_exit() const {
66     return exit_;
67   }
68 
69   std::mutex mutex_;
70   std::condition_variable cond_;
71 
72  private:
73   void InternalRoutine();
74 
75   std::string name_;
76   int priority_;
77 
78   std::unique_ptr<std::thread> thread_;
79   bool is_rt_;
80   bool exit_;
81   bool initialized_;
82 };
83 }  // namespace android
84 #endif
85