From 32e581636f66504daa1a76afcc766be2a4b8a9de Mon Sep 17 00:00:00 2001 From: Gaurav-Aggarwal-AWS <33462878+aggarg@users.noreply.github.com> Date: Thu, 24 Jul 2025 11:07:27 +0530 Subject: [PATCH] Delete thread key on process exit (#1297) Previously, the shared thread key was deleted in xPortStartScheduler after scheduler was ended. This created a race condition where prvThreadKeyDestructor (responsible for freeing thread-specific heap memory) would not be called if xPortStartScheduler deleted the key before the last task deletion, as destructors are not invoked after key deletion (see https://github.com/walac/glibc/blob/master/nptl/pthread_create.c#L145-L150). Move thread key deletion to process exit to ensure all thread-specific memory is properly freed. Signed-off-by: Gaurav Aggarwal --- portable/ThirdParty/GCC/Posix/port.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/portable/ThirdParty/GCC/Posix/port.c b/portable/ThirdParty/GCC/Posix/port.c index d0b81dc1e..2342f6034 100644 --- a/portable/ThirdParty/GCC/Posix/port.c +++ b/portable/ThirdParty/GCC/Posix/port.c @@ -140,6 +140,8 @@ static void prvThreadKeyDestructor( void * pvData ) static void prvInitThreadKey( void ) { pthread_key_create( &xThreadKey, prvThreadKeyDestructor ); + /* Destroy xThreadKey when the process exits. */ + atexit( prvDestroyThreadKey ); } /*-----------------------------------------------------------*/ @@ -315,8 +317,6 @@ BaseType_t xPortStartScheduler( void ) /* Restore original signal mask. */ ( void ) pthread_sigmask( SIG_SETMASK, &xSchedulerOriginalSignalMask, NULL ); - prvDestroyThreadKey(); - return 0; } /*-----------------------------------------------------------*/