• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2017 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 #ifndef ANDROID_HARDWARE_BROADCASTRADIO_COMMON_WORKERTHREAD_H
17 #define ANDROID_HARDWARE_BROADCASTRADIO_COMMON_WORKERTHREAD_H
18 
19 #include <chrono>
20 #include <queue>
21 #include <thread>
22 
23 namespace android {
24 
25 class WorkerThread {
26    public:
27     WorkerThread();
28     virtual ~WorkerThread();
29 
30     void schedule(std::function<void()> task, std::chrono::milliseconds delay);
31     void cancelAll();
32 
33    private:
34     struct Task {
35         std::chrono::time_point<std::chrono::steady_clock> when;
36         std::function<void()> what;
37     };
38     friend bool operator<(const Task& lhs, const Task& rhs);
39 
40     std::atomic<bool> mIsTerminating;
41     std::mutex mMut;
42     std::condition_variable mCond;
43     std::thread mThread;
44     std::priority_queue<Task> mTasks;
45 
46     void threadLoop();
47 };
48 
49 }  // namespace android
50 
51 #endif  // ANDROID_HARDWARE_BROADCASTRADIO_COMMON_WORKERTHREAD_H
52