Merge pull request #175 from bjackman/logcat-race

Fix race in LogcatMonitor
diff --git a/devlib/utils/android.py b/devlib/utils/android.py
index 286c3fe..6846686 100644
--- a/devlib/utils/android.py
+++ b/devlib/utils/android.py
@@ -549,6 +549,7 @@
 
         self.target = target
 
+        self._started = threading.Event()
         self._stopped = threading.Event()
         self._match_found = threading.Event()
 
@@ -584,12 +585,21 @@
         logger.debug('logcat command ="{}"'.format(logcat_cmd))
         self._logcat = self.target.background(logcat_cmd)
 
+        self._started.set()
+
         while not self._stopped.is_set():
             line = self._logcat.stdout.readline(1024)
             if line:
                 self._add_line(line)
 
     def stop(self):
+        if not self.is_alive():
+            logger.warning('LogcatMonitor.stop called before start')
+            return
+
+        # Make sure we've started before we try to kill anything
+        self._started.wait()
+
         # Kill the underlying logcat process
         # This will unblock self._logcat.stdout.readline()
         host.kill_children(self._logcat.pid)
@@ -620,7 +630,7 @@
         with self._datalock:
             while not self._lines.empty():
                 self._lines.get()
-                
+
             with open(self._logfile, 'w') as fh:
                 pass