blob: 31f4d3f83e44d04e30d9b233a72eab96b6b7b979 [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
34WorkerThread::WorkerThread() : mIsTerminating(false), mThread(&WorkerThread::threadLoop, this) {}
35
36WorkerThread::~WorkerThread() {
Tomasz Wasilczyk48377552017-06-22 10:45:33 -070037 {
38 lock_guard<mutex> lk(mMut);
39 mIsTerminating = true;
40 mCond.notify_one();
41 }
42 mThread.join();
43}
44
45void WorkerThread::schedule(function<void()> task, milliseconds delay) {
Tomasz Wasilczyk48377552017-06-22 10:45:33 -070046 auto when = steady_clock::now() + delay;
47
48 lock_guard<mutex> lk(mMut);
49 mTasks.push(Task({when, task}));
50 mCond.notify_one();
51}
52
53void WorkerThread::cancelAll() {
Tomasz Wasilczyk48377552017-06-22 10:45:33 -070054 lock_guard<mutex> lk(mMut);
55 priority_queue<Task>().swap(mTasks); // empty queue
56}
57
58void WorkerThread::threadLoop() {
Tomasz Wasilczyk48377552017-06-22 10:45:33 -070059 while (!mIsTerminating) {
60 unique_lock<mutex> lk(mMut);
61 if (mTasks.empty()) {
62 mCond.wait(lk);
63 continue;
64 }
65
66 auto task = mTasks.top();
67 if (task.when > steady_clock::now()) {
68 mCond.wait_until(lk, task.when);
69 continue;
70 }
71
72 mTasks.pop();
73 lk.unlock(); // what() might need to schedule another task
74 task.what();
75 }
76}
77
78} // namespace android