blob: d1a63d07eeb51606cfaec4e1d5f63ff22a66e1df [file] [log] [blame]
Ilya Matyukhin1f3c8522021-02-12 12:56:02 -08001/*
2 * Copyright (C) 2021 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
17#include "WorkerThread.h"
18
19namespace aidl::android::hardware::biometrics::fingerprint {
20
21// It's important that mThread is initialized after everything else because it runs a member
22// function that may use any member of this class.
23WorkerThread::WorkerThread(size_t maxQueueSize)
24 : mMaxSize(maxQueueSize),
25 mIsDestructing(false),
26 mQueue(),
27 mQueueMutex(),
28 mQueueCond(),
29 mThread(&WorkerThread::threadFunc, this) {}
30
31WorkerThread::~WorkerThread() {
32 // This is a signal for threadFunc to terminate as soon as possible, and a hint for schedule
33 // that it doesn't need to do any work.
34 mIsDestructing = true;
35 mQueueCond.notify_all();
36 mThread.join();
37}
38
Ilya Matyukhin4f5d6802021-02-22 13:10:55 -080039bool WorkerThread::schedule(std::unique_ptr<Callable> task) {
Ilya Matyukhin1f3c8522021-02-12 12:56:02 -080040 if (mIsDestructing) {
41 return false;
42 }
43
44 std::unique_lock<std::mutex> lock(mQueueMutex);
45 if (mQueue.size() >= mMaxSize) {
46 return false;
47 }
48 mQueue.push_back(std::move(task));
49 lock.unlock();
50 mQueueCond.notify_one();
51 return true;
52}
53
54void WorkerThread::threadFunc() {
55 while (!mIsDestructing) {
56 std::unique_lock<std::mutex> lock(mQueueMutex);
57 mQueueCond.wait(lock, [this] { return !mQueue.empty() || mIsDestructing; });
58 if (mIsDestructing) {
59 return;
60 }
Ilya Matyukhin4f5d6802021-02-22 13:10:55 -080061 std::unique_ptr<Callable> task = std::move(mQueue.front());
Ilya Matyukhin1f3c8522021-02-12 12:56:02 -080062 mQueue.pop_front();
63 lock.unlock();
Ilya Matyukhin4f5d6802021-02-22 13:10:55 -080064 (*task)();
Ilya Matyukhin1f3c8522021-02-12 12:56:02 -080065 }
66}
67
68} // namespace aidl::android::hardware::biometrics::fingerprint