Merge changes I6c6bf61b,I3fb0b3a8 am: 3160a25010 am: 9d7880fe96 am: 14f749c2c4
am: 2d30a74181

Change-Id: I57a3916c312b8cc23c616232e84ad6c5507b5a39
diff --git a/adb_utils.h b/adb_utils.h
index 20c63b3..11c0ec9 100644
--- a/adb_utils.h
+++ b/adb_utils.h
@@ -74,13 +74,18 @@
 
     template <typename Fn>
     void PopAll(Fn fn) {
-        std::unique_lock<std::mutex> lock(mutex);
-        cv.wait(lock, [this]() { return !queue.empty(); });
+        std::vector<T> popped;
 
-        for (const T& t : queue) {
+        {
+            std::unique_lock<std::mutex> lock(mutex);
+            cv.wait(lock, [this]() { return !queue.empty(); });
+            popped = std::move(queue);
+            queue.clear();
+        }
+
+        for (const T& t : popped) {
             fn(t);
         }
-        queue.clear();
     }
 };
 
diff --git a/client/usb_libusb.cpp b/client/usb_libusb.cpp
index 7e77b5e..b2fdc07 100644
--- a/client/usb_libusb.cpp
+++ b/client/usb_libusb.cpp
@@ -422,8 +422,10 @@
         if (!it->second->device_handle) {
             // If the handle is null, we were never able to open the device.
             unregister_usb_transport(it->second.get());
+            usb_handles.erase(it);
+        } else {
+            // Closure of the transport will erase the usb_handle.
         }
-        usb_handles.erase(it);
     }
 }