blob: bd42240de511e4e25188423b2a6f39336c911750 [file] [log] [blame]
Yifan Hong5e2318c2016-10-27 17:19:21 -07001/*
2 * Copyright (C) 2016 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 <hidl/TaskRunner.h>
Steven Morelandc03f9432017-08-16 14:17:49 -070018
Chia-I Wu05420042017-09-11 09:55:43 -070019#include <utils/AndroidThreads.h>
Steven Morelandc03f9432017-08-16 14:17:49 -070020#include "SynchronizedQueue.h"
21
Yifan Hong5e2318c2016-10-27 17:19:21 -070022#include <thread>
23
24namespace android {
25namespace hardware {
Yifan Hong0a351392017-03-20 17:17:52 -070026namespace details {
Yifan Hong5e2318c2016-10-27 17:19:21 -070027
28TaskRunner::TaskRunner() {
Yifan Hong6f667542017-03-20 19:04:05 -070029}
30
31void TaskRunner::start(size_t limit) {
32 mQueue = std::make_shared<SynchronizedQueue<Task>>(limit);
Yifan Hong5e2318c2016-10-27 17:19:21 -070033}
Yifan Hong8184c122017-03-20 18:26:43 -070034
Yifan Hong5e2318c2016-10-27 17:19:21 -070035TaskRunner::~TaskRunner() {
Yifan Hong6f667542017-03-20 19:04:05 -070036 if (mQueue) {
37 mQueue->push(nullptr);
38 }
Yifan Hong5e2318c2016-10-27 17:19:21 -070039}
40
Steven Moreland0540d282017-05-08 16:03:11 -070041bool TaskRunner::push(const Task &t) {
Steven Morelandc03f9432017-08-16 14:17:49 -070042 if (mQueue == nullptr || !t) {
43 return false;
44 }
45
46 {
47 std::unique_lock<std::mutex> lock = mQueue->lock();
48
49 if (!mQueue->isInitializedLocked()) {
50 // Allow the thread to continue running in background;
51 // TaskRunner do not care about the std::thread object.
52 std::thread{[q = mQueue] {
Chia-I Wu05420042017-09-11 09:55:43 -070053 androidSetThreadName("HIDL TaskRunner");
54
Steven Morelandc03f9432017-08-16 14:17:49 -070055 Task nextTask;
56 while (!!(nextTask = q->wait_pop())) {
57 nextTask();
58 }
59 }}.detach();
60
61 mQueue->setInitializedLocked(true);
62 }
63 }
64
65 return this->mQueue->push(t);
Steven Moreland0540d282017-05-08 16:03:11 -070066}
67
Yifan Hong0a351392017-03-20 17:17:52 -070068} // namespace details
Yifan Hong5e2318c2016-10-27 17:19:21 -070069} // namespace hardware
70} // namespace android
71