fix thread pool can't exit

This commit is contained in:
tqcq 2024-05-01 09:44:45 +08:00
parent 1eb66fb4dc
commit 50c3456f65

View File

@ -13,7 +13,7 @@ ThreadPool::ThreadPool(int num_threads) : delayed_thread_(sled::Thread::Create()
auto state = std::make_shared<State>();
for (int i = 0; i < num_threads; i++) {
threads_.emplace_back(std::thread([state] {
state->idle++;
state->idle.fetch_add(1, std::memory_order_relaxed);
while (state->is_running) {
std::function<void()> task;
sled::Location loc = SLED_FROM_HERE;
@ -26,10 +26,16 @@ ThreadPool::ThreadPool(int num_threads) : delayed_thread_(sled::Thread::Create()
loc = state->task_queue.front().second;
state->task_queue.pop();
}
// FIXME: can't exit if task add self, must check <is_running>
if (!state->is_running) {
state->idle.fetch_sub(1, std::memory_order_relaxed);
break;
}
if (!state->task_queue.empty()) { state->cv.NotifyOne(); }
}
if (task) {
state->idle--;
state->idle.fetch_sub(1, std::memory_order_release);
try {
task();
} catch (const std::exception &e) {
@ -37,7 +43,7 @@ ThreadPool::ThreadPool(int num_threads) : delayed_thread_(sled::Thread::Create()
} catch (...) {
LOGE(kTag, "ThreadPool::ThreadPool() task unknown exception, from={}", loc.ToString());
}
state->idle++;
state->idle.fetch_add(1, std::memory_order_relaxed);
}
}
}));