--- mysql-connector-c-6.0.2/mysys/my_thr_init.c.orig	2009-08-07 14:31:12.000000000 +0200
+++ mysql-connector-c-6.0.2/mysys/my_thr_init.c	2012-09-07 21:37:39.840742330 +0200
@@ -47,6 +47,7 @@ pthread_mutexattr_t my_fast_mutexattr;
 #ifdef PTHREAD_ERRORCHECK_MUTEX_INITIALIZER_NP
 pthread_mutexattr_t my_errorcheck_mutexattr;
 #endif
+static void thread_cleanup(void* data);
 #ifdef _MSC_VER
 static void install_sigabrt_handler();
 #endif
@@ -118,7 +119,7 @@ my_bool my_thread_global_init(void)
   int pth_ret;
   thd_lib_detected= get_thread_lib();
 
-  if ((pth_ret= pthread_key_create(&THR_KEY_mysys, NULL)) != 0)
+  if ((pth_ret= pthread_key_create(&THR_KEY_mysys, thread_cleanup)) != 0)
   {
     fprintf(stderr,"Can't initialize threads: error %d\n", pth_ret);
     return 1;
@@ -256,9 +257,9 @@ void my_thread_global_end(void)
 
 void my_thread_destroy_mutex(void)
 {
+#ifdef SAFE_MUTEX
   struct st_my_thread_var *tmp;
   tmp= my_pthread_getspecific(struct st_my_thread_var*,THR_KEY_mysys);
-#ifdef SAFE_MUTEX
   if (tmp)
   {
     safe_mutex_free_deadlock_data(&tmp->mutex);
@@ -377,6 +378,20 @@ void my_thread_end(void)
   fprintf(stderr,"my_thread_end(): tmp: 0x%lx  pthread_self: 0x%lx  thread_id: %ld\n",
 	  (long) tmp, (long) pthread_self(), tmp ? (long) tmp->id : 0L);
 #endif
+  pthread_setspecific(THR_KEY_mysys,0);
+
+  /* Cleanup using the Posix 1003.1 standard mechanism with pthread_key_create */
+  thread_cleanup(tmp);
+}
+
+/*
+  Do the real thread memory cleanup.  This is called explictly by
+  my_thread_end() or by the Posix 1003.1 thread cleanup mechanism.
+*/
+static void thread_cleanup(void* data)
+{
+  struct st_my_thread_var *tmp = (struct st_my_thread_var*) data;
+
   if (tmp && tmp->init)
   {
 
@@ -404,7 +419,7 @@ void my_thread_end(void)
     bfill(tmp, sizeof(tmp), 0x8F);
 #endif
     free(tmp);
-    pthread_setspecific(THR_KEY_mysys,0);
+
     /*
       Decrement counter for number of running threads. We are using this
       in my_thread_global_end() to wait until all threads have called
@@ -415,11 +430,7 @@ void my_thread_end(void)
     DBUG_ASSERT(THR_thread_count != 0);
     if (--THR_thread_count == 0)
       pthread_cond_signal(&THR_COND_threads);
-   pthread_mutex_unlock(&THR_LOCK_threads);
-  }
-  else
-  {
-    pthread_setspecific(THR_KEY_mysys,0);
+    pthread_mutex_unlock(&THR_LOCK_threads);
   }
 }
 
