blob: d4357bf37df1191c982f85208d3f8b9948ce84fe [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
19#include "SynchronizedQueue.h"
20
Yifan Hong5e2318c2016-10-27 17:19:21 -070021#include <thread>
22
23namespace android {
24namespace hardware {
Yifan Hong0a351392017-03-20 17:17:52 -070025namespace details {
Yifan Hong5e2318c2016-10-27 17:19:21 -070026
27TaskRunner::TaskRunner() {
Yifan Hong6f667542017-03-20 19:04:05 -070028}
29
30void TaskRunner::start(size_t limit) {
31 mQueue = std::make_shared<SynchronizedQueue<Task>>(limit);
Yifan Hong5e2318c2016-10-27 17:19:21 -070032}
Yifan Hong8184c122017-03-20 18:26:43 -070033
Yifan Hong5e2318c2016-10-27 17:19:21 -070034TaskRunner::~TaskRunner() {
Yifan Hong6f667542017-03-20 19:04:05 -070035 if (mQueue) {
36 mQueue->push(nullptr);
37 }
Yifan Hong5e2318c2016-10-27 17:19:21 -070038}
39
Steven Moreland0540d282017-05-08 16:03:11 -070040bool TaskRunner::push(const Task &t) {
Steven Morelandc03f9432017-08-16 14:17:49 -070041 if (mQueue == nullptr || !t) {
42 return false;
43 }
44
45 {
46 std::unique_lock<std::mutex> lock = mQueue->lock();
47
48 if (!mQueue->isInitializedLocked()) {
49 // Allow the thread to continue running in background;
50 // TaskRunner do not care about the std::thread object.
51 std::thread{[q = mQueue] {
52 Task nextTask;
53 while (!!(nextTask = q->wait_pop())) {
54 nextTask();
55 }
56 }}.detach();
57
58 mQueue->setInitializedLocked(true);
59 }
60 }
61
62 return this->mQueue->push(t);
Steven Moreland0540d282017-05-08 16:03:11 -070063}
64
Yifan Hong0a351392017-03-20 17:17:52 -070065} // namespace details
Yifan Hong5e2318c2016-10-27 17:19:21 -070066} // namespace hardware
67} // namespace android
68