blob: dd87f538eac6a15d3393c9e4a8daabb193971bd0 [file] [log] [blame]
Tomasz Wasilczyk48377552017-06-22 10:45:33 -07001/*
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
Tomasz Wasilczykc1763a62017-07-25 10:01:17 -070017#include <broadcastradio-utils/WorkerThread.h>
Tomasz Wasilczyk48377552017-06-22 10:45:33 -070018
Tomasz Wasilczyk48377552017-06-22 10:45:33 -070019namespace android {
20
21using std::chrono::milliseconds;
22using std::chrono::steady_clock;
23using std::function;
24using std::lock_guard;
25using std::mutex;
26using std::priority_queue;
27using std::this_thread::sleep_for;
28using std::unique_lock;
29
30bool operator<(const WorkerThread::Task& lhs, const WorkerThread::Task& rhs) {
31 return lhs.when > rhs.when;
32}
33
Keith Mokb1210922022-05-06 19:25:54 +000034WorkerThread::WorkerThread() : mIsTerminating(false) {
35 // putting mThread in constructor instead of initializer list
36 // to ensure all class members are init before mThread starts
37 mThread = std::thread(&WorkerThread::threadLoop, this);
38}
Tomasz Wasilczyk48377552017-06-22 10:45:33 -070039
40WorkerThread::~WorkerThread() {
Tomasz Wasilczyk48377552017-06-22 10:45:33 -070041 {
42 lock_guard<mutex> lk(mMut);
43 mIsTerminating = true;
44 mCond.notify_one();
45 }
46 mThread.join();
47}
48
49void WorkerThread::schedule(function<void()> task, milliseconds delay) {
Tomasz Wasilczyk48377552017-06-22 10:45:33 -070050 auto when = steady_clock::now() + delay;
51
52 lock_guard<mutex> lk(mMut);
53 mTasks.push(Task({when, task}));
54 mCond.notify_one();
55}
56
57void WorkerThread::cancelAll() {
Tomasz Wasilczyk48377552017-06-22 10:45:33 -070058 lock_guard<mutex> lk(mMut);
59 priority_queue<Task>().swap(mTasks); // empty queue
60}
61
62void WorkerThread::threadLoop() {
Tomasz Wasilczyk48377552017-06-22 10:45:33 -070063 while (!mIsTerminating) {
64 unique_lock<mutex> lk(mMut);
65 if (mTasks.empty()) {
66 mCond.wait(lk);
67 continue;
68 }
69
70 auto task = mTasks.top();
71 if (task.when > steady_clock::now()) {
72 mCond.wait_until(lk, task.when);
73 continue;
74 }
75
76 mTasks.pop();
77 lk.unlock(); // what() might need to schedule another task
78 task.what();
79 }
80}
81
82} // namespace android