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 schedule(std::function<void()> task, std::function<void()> cancelTask, 32 std::chrono::milliseconds delay); 33 void cancelAll(); 34 35 private: 36 struct Task { 37 std::chrono::time_point<std::chrono::steady_clock> when; 38 std::function<void()> what; 39 std::function<void()> onCanceled; 40 }; 41 friend bool operator<(const Task& lhs, const Task& rhs); 42 43 std::atomic<bool> mIsTerminating; 44 std::mutex mMut; 45 std::condition_variable mCond; 46 std::thread mThread; 47 std::priority_queue<Task> mTasks; 48 49 void threadLoop(); 50 }; 51 52 } // namespace android 53 54 #endif // ANDROID_HARDWARE_BROADCASTRADIO_COMMON_WORKERTHREAD_H 55