Fix threading problem that resulted in the wakelock being held too long.

In some circumstances we were calling wait after we had been signalled, causing
us to wait until we are signalled again (while holding a wakelock).
Now we only want to wait in the deferred action thread if no events are pending
and only hold the wakelock while not waiting.

BUG: 3127617

Change-Id: I4c6886b2bbdcbcb2c0cf348d89bc5408f0d875b9
Signed-off-by: Mike Lockwood <lockwood@google.com>
diff --git a/loc_api/libloc_api/loc_eng.cpp b/loc_api/libloc_api/loc_eng.cpp
index ed27824..8a3d412 100755
--- a/loc_api/libloc_api/loc_eng.cpp
+++ b/loc_api/libloc_api/loc_eng.cpp
@@ -1449,11 +1449,17 @@
         // Wait until we are signalled to do a deferred action, or exit
         pthread_mutex_lock(&loc_eng_data.deferred_action_mutex);
 
-        if (loc_eng_data.deferred_action_flags == 0)
+        // If we have an event we should process it immediately,
+        // otherwise wait until we are signalled
+        if (loc_eng_data.deferred_action_flags == 0) {
+            // do not hold a wake lock while waiting for an event...
             loc_eng_data.release_wakelock_cb();
-
-        pthread_cond_wait(&loc_eng_data.deferred_action_cond,
-                            &loc_eng_data.deferred_action_mutex);
+            pthread_cond_wait(&loc_eng_data.deferred_action_cond,
+                                &loc_eng_data.deferred_action_mutex);
+            // but after we are signalled reacquire the wake lock
+            // until we are done processing the event.
+            loc_eng_data.acquire_wakelock_cb();
+        }
 
         if (loc_eng_data.deferred_action_flags & DEFERRED_ACTION_QUIT)
         {