[llvm] [Support] Join threads when stopping the ThreadPoolExecutor (PR #166054)
Maurice Heumann via llvm-commits
llvm-commits at lists.llvm.org
Mon Nov 3 10:59:49 PST 2025
https://github.com/momo5502 updated https://github.com/llvm/llvm-project/pull/166054
>From 363f3b59f2ee910d49ce24c01c64b3c0f2391a95 Mon Sep 17 00:00:00 2001
From: momo5502 <mauriceheumann at gmail.com>
Date: Sun, 2 Nov 2025 11:56:45 +0100
Subject: [PATCH] [Support] Join threads when stopping ThreadPoolExecutor
---
llvm/lib/Support/Parallel.cpp | 20 +++++++++++++-------
1 file changed, 13 insertions(+), 7 deletions(-)
diff --git a/llvm/lib/Support/Parallel.cpp b/llvm/lib/Support/Parallel.cpp
index 8e0c724accb36..ca03d6747cc85 100644
--- a/llvm/lib/Support/Parallel.cpp
+++ b/llvm/lib/Support/Parallel.cpp
@@ -57,6 +57,7 @@ class ThreadPoolExecutor : public Executor {
if (S.UseJobserver)
TheJobserver = JobserverClient::getInstance();
+ ThreadsCreatedFuture = ThreadsCreated.get_future();
ThreadCount = S.compute_thread_count();
// Spawn all but one of the threads in another thread as spawning threads
// can take a while.
@@ -84,24 +85,28 @@ class ThreadPoolExecutor : public Executor {
void stop() {
{
std::lock_guard<std::mutex> Lock(Mutex);
- if (Stop)
- return;
Stop = true;
}
+
+ ThreadsCreatedFuture.wait();
Cond.notify_all();
- ThreadsCreated.get_future().wait();
- }
- ~ThreadPoolExecutor() override {
- stop();
+ std::vector<std::thread> ThreadsToJoin;
+ {
+ std::lock_guard<std::mutex> Lock(Mutex);
+ ThreadsToJoin.swap(Threads);
+ }
+
std::thread::id CurrentThreadId = std::this_thread::get_id();
- for (std::thread &T : Threads)
+ for (std::thread &T : ThreadsToJoin)
if (T.get_id() == CurrentThreadId)
T.detach();
else
T.join();
}
+ ~ThreadPoolExecutor() override { stop(); }
+
struct Creator {
static void *call() { return new ThreadPoolExecutor(strategy); }
};
@@ -187,6 +192,7 @@ class ThreadPoolExecutor : public Executor {
std::mutex Mutex;
std::condition_variable Cond;
std::promise<void> ThreadsCreated;
+ std::future<void> ThreadsCreatedFuture;
std::vector<std::thread> Threads;
unsigned ThreadCount;
More information about the llvm-commits
mailing list