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 #include <android-base/thread_annotations.h> 24 25 namespace android { 26 27 class WorkerThread { 28 public: 29 WorkerThread(); 30 virtual ~WorkerThread(); 31 32 void schedule(std::function<void()> task, std::chrono::milliseconds delay); 33 void schedule(std::function<void()> task, std::function<void()> cancelTask, 34 std::chrono::milliseconds delay); 35 void cancelAll(); 36 37 private: 38 struct Task { 39 std::chrono::time_point<std::chrono::steady_clock> when; 40 std::function<void()> what; 41 std::function<void()> onCanceled; 42 }; 43 friend bool operator<(const Task& lhs, const Task& rhs); 44 45 std::mutex mMut; 46 bool mIsTerminating GUARDED_BY(mMut); 47 std::condition_variable mCond GUARDED_BY(mMut); 48 std::thread mThread; 49 std::priority_queue<Task> mTasks GUARDED_BY(mMut); 50 51 void threadLoop(); 52 }; 53 54 } // namespace android 55 56 #endif // ANDROID_HARDWARE_BROADCASTRADIO_COMMON_WORKERTHREAD_H 57