From 0a2c5e3ca760494e07dd0059e5dbfea9c9c04d3d Mon Sep 17 00:00:00 2001 From: tqcq <99722391+tqcq@users.noreply.github.com> Date: Wed, 24 Apr 2024 15:36:09 +0800 Subject: [PATCH] fix crash for static ThreadPool --- src/sled/futures/future.cc | 23 +++++++++++++++-------- 1 file changed, 15 insertions(+), 8 deletions(-) diff --git a/src/sled/futures/future.cc b/src/sled/futures/future.cc index 4a639e1..71ae37a 100644 --- a/src/sled/futures/future.cc +++ b/src/sled/futures/future.cc @@ -14,23 +14,30 @@ DecrementFuturesUsage() }// namespace future_detail -static ThreadPool g_default_thread_pool; -TaskQueueBase *g_default_scheduler = &g_default_thread_pool; +static std::atomic g_default_scheduler{nullptr}; +// static ThreadPool default_thread_pool; +static std::unique_ptr g_default_thread; void SetDefaultScheduler(TaskQueueBase *scheduler) noexcept { - if (scheduler == nullptr) { - g_default_scheduler = &g_default_thread_pool; - } else { - g_default_scheduler = scheduler; - } + SLED_ASSERT(scheduler, "scheduler is nullptr"); + g_default_scheduler.store(scheduler, std::memory_order_release); } TaskQueueBase * GetDefaultScheduler() noexcept { - return g_default_scheduler; + static std::once_flag flag; + std::call_once(flag, [&] { + g_default_thread = sled::Thread::Create(); + g_default_thread->Start(); + TaskQueueBase *null_scheduler = nullptr; + while (g_default_scheduler.load() == nullptr) { + g_default_scheduler.compare_exchange_weak(null_scheduler, g_default_thread.get()); + } + }); + return g_default_scheduler.load(std::memory_order_acquire); } }// namespace sled