Loading...
pthreads/pthread_tsd.c Libc-498 Libc-583
--- Libc/Libc-498/pthreads/pthread_tsd.c
+++ Libc/Libc-583/pthreads/pthread_tsd.c
@@ -187,11 +187,10 @@
 	int i, j;
 	void *param;
 
+	/* destroy dynamic keys first */
 	for (j = 0;  j < PTHREAD_DESTRUCTOR_ITERATIONS;  j++)
 	{
-		/* The first slot is reserved for pthread_self() */
-
-		for (i = __pthread_tsd_first;  i <= __pthread_tsd_max;  i++)
+		for (i = __pthread_tsd_start;  i <= self->max_tsd_key;  i++)
 		{
 			if (_pthread_keys[i].created && (param = self->tsd[i]))
 			{
@@ -202,7 +201,16 @@
 				}
 			}
 		}
-		for (i = __pthread_tsd_start;  i <= self->max_tsd_key;  i++)
+	}
+
+	self->max_tsd_key = 0;
+
+	/* 
+	 * The first slot is reserved for pthread_self() and there is no cleanup on it.
+	 * Destroy rest of the static keys next only if any destructors registered.
+	 */
+	for (j = 0;  j < PTHREAD_DESTRUCTOR_ITERATIONS;  j++) {
+		for (i = __pthread_tsd_first;  i <= __pthread_tsd_max;  i++)
 		{
 			if (_pthread_keys[i].created && (param = self->tsd[i]))
 			{
@@ -214,7 +222,6 @@
 			}
 		}
 	}
-	self->max_tsd_key = 0;
 }
 
 int