From e951ffbe576109bf8873eae1e0ee522fca73840c Mon Sep 17 00:00:00 2001 From: wuminghui Date: Tue, 18 Mar 2025 11:50:31 +0800 Subject: [PATCH] Fix compiler optimize thread local variable access `bthread_usleep`/`bthread_yield` contains access to TLS variables. In LTO mode, exceptions may occur due to cross-module optimization. For example, bthread_usleep is inlined into WatchConnections, the compiler(clang-17.0.6) cache the address outside the loop, triggering the error mentioned in #2156. --- src/bthread/bthread.cpp | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/bthread/bthread.cpp b/src/bthread/bthread.cpp index e124f4bc6f..1ec4faaa91 100644 --- a/src/bthread/bthread.cpp +++ b/src/bthread/bthread.cpp @@ -70,6 +70,7 @@ pthread_mutex_t g_task_control_mutex = PTHREAD_MUTEX_INITIALIZER; TaskControl* g_task_control = NULL; extern BAIDU_THREAD_LOCAL TaskGroup* tls_task_group; +EXTERN_BAIDU_VOLATILE_THREAD_LOCAL(TaskGroup*, tls_task_group); extern void (*g_worker_startfn)(); extern void (*g_tagged_worker_startfn)(bthread_tag_t); extern void* (*g_create_span_func)(); @@ -521,7 +522,7 @@ int bthread_timer_del(bthread_timer_t id) { } int bthread_usleep(uint64_t microseconds) { - bthread::TaskGroup* g = bthread::tls_task_group; + bthread::TaskGroup* g = bthread::BAIDU_GET_VOLATILE_THREAD_LOCAL(tls_task_group); if (NULL != g && !g->is_current_pthread_task()) { return bthread::TaskGroup::usleep(&g, microseconds); } @@ -529,7 +530,7 @@ int bthread_usleep(uint64_t microseconds) { } int bthread_yield(void) { - bthread::TaskGroup* g = bthread::tls_task_group; + bthread::TaskGroup* g = bthread::BAIDU_GET_VOLATILE_THREAD_LOCAL(tls_task_group); if (NULL != g && !g->is_current_pthread_task()) { bthread::TaskGroup::yield(&g); return 0;