TaskRunner.cpp 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. /*
  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. #include <hidl/TaskRunner.h>
  17. #include <utils/AndroidThreads.h>
  18. #include "SynchronizedQueue.h"
  19. #include <thread>
  20. namespace android {
  21. namespace hardware {
  22. namespace details {
  23. TaskRunner::TaskRunner() {
  24. }
  25. void TaskRunner::start(size_t limit) {
  26. mQueue = std::make_shared<SynchronizedQueue<Task>>(limit);
  27. }
  28. TaskRunner::~TaskRunner() {
  29. if (mQueue) {
  30. mQueue->push(nullptr);
  31. }
  32. }
  33. bool TaskRunner::push(const Task &t) {
  34. if (mQueue == nullptr || !t) {
  35. return false;
  36. }
  37. {
  38. std::unique_lock<std::mutex> lock = mQueue->lock();
  39. if (!mQueue->isInitializedLocked()) {
  40. // Allow the thread to continue running in background;
  41. // TaskRunner do not care about the std::thread object.
  42. std::thread{[q = mQueue] {
  43. androidSetThreadName("HIDL TaskRunner");
  44. Task nextTask;
  45. while (!!(nextTask = q->wait_pop())) {
  46. nextTask();
  47. }
  48. }}.detach();
  49. mQueue->setInitializedLocked(true);
  50. }
  51. }
  52. return this->mQueue->push(t);
  53. }
  54. } // namespace details
  55. } // namespace hardware
  56. } // namespace android