logd: persistent reader threads

(cherry picked from commit c113c5813ebd620e0bc60ece9a32ea14c08ea237)

Bug: 16822776
Change-Id: I5bea468a41089b51108880044f32e2b2df1278e7
diff --git a/logd/LogTimes.cpp b/logd/LogTimes.cpp
index e7e3ec2..ea4e8c8 100644
--- a/logd/LogTimes.cpp
+++ b/logd/LogTimes.cpp
@@ -33,7 +33,6 @@
         , mRelease(false)
         , mError(false)
         , threadRunning(false)
-        , threadTriggered(true)
         , mReader(reader)
         , mLogMask(logMask)
         , mPid(pid)
@@ -45,7 +44,9 @@
         , mStart(start)
         , mNonBlock(nonBlock)
         , mEnd(CLOCK_MONOTONIC)
-{ }
+{
+        pthread_cond_init(&threadTriggeredCondition, NULL);
+}
 
 void LogTimeEntry::startReader_Locked(void) {
     pthread_attr_t attr;
@@ -74,7 +75,6 @@
 
     lock();
 
-    me->threadRunning = false;
     if (me->mNonBlock) {
         me->error_Locked();
     }
@@ -103,6 +103,7 @@
         client->decRef();
     }
 
+    me->threadRunning = false;
     me->decRef_Locked();
 
     unlock();
@@ -118,7 +119,7 @@
     SocketClient *client = me->mClient;
     if (!client) {
         me->error();
-        pthread_exit(NULL);
+        return NULL;
     }
 
     LogBuffer &logbuf = me->mReader.logbuf();
@@ -127,12 +128,7 @@
 
     lock();
 
-    me->threadTriggered = true;
-
-    while(me->threadTriggered && !me->isError_Locked()) {
-
-        me->threadTriggered = false;
-
+    while (me->threadRunning && !me->isError_Locked()) {
         log_time start = me->mStart;
 
         unlock();
@@ -142,24 +138,21 @@
         }
         start = logbuf.flushTo(client, start, privileged, FilterSecondPass, me);
 
+        lock();
+
         if (start == LogBufferElement::FLUSH_ERROR) {
-            me->error();
+            me->error_Locked();
         }
 
-        if (me->mNonBlock) {
-            lock();
+        if (me->mNonBlock || !me->threadRunning || me->isError_Locked()) {
             break;
         }
 
-        sched_yield();
-
-        lock();
+        pthread_cond_wait(&me->threadTriggeredCondition, &timesLock);
     }
 
     unlock();
 
-    pthread_exit(NULL);
-
     pthread_cleanup_pop(true);
 
     return NULL;