Joining the thread before the MtpFfsHandle object's destruction

We're detaching the thread t in sendEvent. This means the thread
continues to execute independently, even after the MtpFfsHandle object
might have been destroyed. Instead of detaching threads, Join the thread
before MtpFfsHandle object's destruction.
Bug: 355382936
Flag: EXEMPT bug fix
Test: Build mtp_handle_fuzzer and run on the target device
Test: Run mtp in host and device mode

Change-Id: I924704575af89e747793c5d8647570d31cd14af9
diff --git a/media/mtp/MtpFfsHandle.cpp b/media/mtp/MtpFfsHandle.cpp
index 5d68890..979edab 100644
--- a/media/mtp/MtpFfsHandle.cpp
+++ b/media/mtp/MtpFfsHandle.cpp
@@ -297,9 +297,10 @@
 }
 
 void MtpFfsHandle::close() {
-    auto timeout = std::chrono::seconds(2);
-    std::unique_lock lk(m);
-    cv.wait_for(lk, timeout ,[this]{return child_threads==0;});
+    // Join all child threads before destruction
+    for (auto& thread : mChildThreads) {
+        thread.join();
+    }
 
     io_destroy(mCtx);
     closeEndpoints();
@@ -677,12 +678,10 @@
     memcpy(temp, me.data, me.length);
     me.data = temp;
 
-    std::unique_lock lk(m);
-    child_threads++;
-    lk.unlock();
-
     std::thread t([this, me]() { return this->doSendEvent(me); });
-    t.detach();
+
+    // Store the thread object for later joining
+    mChildThreads.emplace_back(std::move(t));
     return 0;
 }
 
@@ -692,11 +691,6 @@
     if (static_cast<unsigned>(ret) != length)
         PLOG(ERROR) << "Mtp error sending event thread!";
     delete[] reinterpret_cast<char*>(me.data);
-
-    std::unique_lock lk(m);
-    child_threads--;
-    lk.unlock();
-    cv.notify_one();
 }
 
 } // namespace android