Make purging clear the current thread cache too.

Bug: 131362671

Test: Ran bionic unit tests.
Test: Wrote a test that did a purge and verified that the tcache->ncached
Test: number went from 3 to 0. Also verified that mallinfo reflects the
Test: cached entries being flushed.
Change-Id: I64e35618fa3b523cf29bdaceedef676abe440dd3
diff --git a/libc/bionic/jemalloc_wrapper.cpp b/libc/bionic/jemalloc_wrapper.cpp
index bc3a9dc..fd99814 100644
--- a/libc/bionic/jemalloc_wrapper.cpp
+++ b/libc/bionic/jemalloc_wrapper.cpp
@@ -103,6 +103,14 @@
     }
     return 1;
   } else if (param == M_PURGE) {
+    // Only clear the current thread cache since there is no easy way to
+    // clear the caches of other threads.
+    // This must be done first so that cleared allocations get purged
+    // in the next calls.
+    if (je_mallctl("thread.tcache.flush", nullptr, nullptr, nullptr, 0) != 0) {
+      return 0;
+    }
+
     unsigned narenas;
     size_t sz = sizeof(unsigned);
     if (je_mallctl("arenas.narenas", &narenas, &sz, nullptr, 0) != 0) {