@@ -163,11 +163,13 @@ mi_decl_cache_align const mi_theap_t _mi_theap_empty_wrong = {
163163
164164// Heap for the main thread
165165
166+ #define MI_THREADID_UNINIT ((mi_threadid_t)(~0))
167+
166168extern mi_decl_hidden mi_decl_cache_align mi_theap_t theap_main ;
167169extern mi_decl_hidden mi_decl_cache_align mi_heap_t heap_main ;
168170
169171static mi_decl_cache_align mi_tld_t tld_main = {
170- 0 , // thread_id
172+ MI_THREADID_UNINIT , // thread_id
171173 0 , // thread_seq
172174 0 , // numa node
173175 & subproc_main , // subproc
@@ -214,7 +216,7 @@ mi_decl_cache_align mi_heap_t heap_main
214216mi_decl_hidden mi_decl_thread mi_theap_t * __mi_theap_main = NULL ;
215217
216218mi_threadid_t _mi_thread_id (void ) mi_attr_noexcept {
217- mi_threadid_t tid = _mi_prim_thread_id ();
219+ const mi_threadid_t tid = _mi_prim_thread_id ();
218220 mi_assert_internal ( (tid & 0x03 ) == 0 ); // mimalloc reserves the bottom 2 bits
219221 return tid ;
220222}
@@ -298,7 +300,7 @@ static void mi_subproc_main_init(void) {
298300
299301// Initialize main tld
300302static void mi_tld_main_init (void ) {
301- if (tld_main .thread_id == 0 ) {
303+ if (tld_main .thread_id == MI_THREADID_UNINIT ) {
302304 tld_main .thread_id = _mi_prim_thread_id ();
303305 mi_lock_init (& tld_main .theaps_lock );
304306 }
@@ -379,17 +381,11 @@ static mi_tld_t* mi_tld_alloc(void) {
379381#define MI_TLD_INVALID ((mi_tld_t*)1)
380382
381383mi_decl_noinline static void mi_tld_free (mi_tld_t * tld ) {
382- mi_lock_done (& tld -> theaps_lock );
383- if (tld != NULL && tld != MI_TLD_INVALID ) {
384- mi_atomic_decrement_relaxed (& tld -> subproc -> thread_count );
385- _mi_meta_free (tld , sizeof (mi_tld_t ), tld -> memid );
386- }
387- #if 0
388- // do not read/write to `thread_tld` on older macOS <= 14 as that will re-initialize the thread local storage
389- // (since we are calling this during pthread shutdown)
390- // (and this could happen on other systems as well, so let's never do it)
391- thread_tld = MI_TLD_INVALID ;
392- #endif
384+ if (tld == NULL || tld == MI_TLD_INVALID ) return ;
385+ mi_atomic_decrement_relaxed (& tld -> subproc -> thread_count );
386+ tld -> thread_id = 0 ;
387+ mi_lock_done (& tld -> theaps_lock );
388+ _mi_meta_free (tld , sizeof (mi_tld_t ), tld -> memid ); // note: safe for static tld_main
393389}
394390
395391// return the thread local heap ensuring it is initialized (and not `NULL` or `&_mi_theap_empty`);
@@ -704,7 +700,7 @@ static void mi_process_setup_auto_thread_done(void) {
704700
705701
706702bool _mi_is_main_thread (void ) {
707- return (tld_main .thread_id == 0 || tld_main .thread_id == _mi_thread_id ());
703+ return (tld_main .thread_id == MI_THREADID_UNINIT || tld_main .thread_id == _mi_thread_id ());
708704}
709705
710706
0 commit comments