Simplify the implementation of TaskRunner.
TestRunner used to hold the std::thread pointer and
a pointer to a boolean flag. Simplify them:
* std::thread* is not needed because detach() allows
the thread to run in background
* bool* is not needed; use a non-callable std::function
to indicate end of queue.
* Use std::shared_ptr instead of raw pointer for mQueue
to avoid weird pointer ownership management.
Test: libhidl_test
Test: hidl_test
Test: boots
Change-Id: I8fe7a6285bc537408ed559499951c17219e0df7f
diff --git a/base/TaskRunner.cpp b/base/TaskRunner.cpp
index 78add4c..cd1df05 100644
--- a/base/TaskRunner.cpp
+++ b/base/TaskRunner.cpp
@@ -22,26 +22,20 @@
namespace details {
TaskRunner::TaskRunner() {
- bool *running = mRunning = new bool();
- SynchronizedQueue<std::function<void(void)>> *q
- = mQueue = new SynchronizedQueue<std::function<void(void)>>();
- mThread = new std::thread([running, q] {
- *running = true;
- while (*running) {
- (q->wait_pop())();
+ mQueue = std::make_shared<SynchronizedQueue<Task>>();
+
+ // Allow the thread to continue running in background;
+ // TaskRunner do not care about the std::thread object.
+ std::thread{[q = mQueue] {
+ Task nextTask;
+ while (!!(nextTask = q->wait_pop())) {
+ nextTask();
}
- delete q;
- delete running;
- });
+ }}.detach();
}
+
TaskRunner::~TaskRunner() {
- bool *running = mRunning;
- std::thread *t = mThread;
- mThread->detach();
- mQueue->push([running, t] {
- *running = false;
- delete t;
- });
+ mQueue->push(nullptr);
}
} // namespace details