Properly cleanup thread-local values for the threads destroying thread_value_t objects
authorTobias Brunner <tobias@strongswan.org>
Thu, 12 Jul 2012 07:34:56 +0000 (09:34 +0200)
committerTobias Brunner <tobias@strongswan.org>
Thu, 12 Jul 2012 07:43:27 +0000 (09:43 +0200)
src/libstrongswan/threading/thread_value.c

index 3fa70ac..190b743 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2009 Tobias Brunner
+ * Copyright (C) 2009-2012 Tobias Brunner
  * Hochschule fuer Technik Rapperswil
  *
  * This program is free software; you can redistribute it and/or modify it
@@ -33,6 +33,11 @@ struct private_thread_value_t {
         */
        pthread_key_t key;
 
+       /**
+        * Destructor to cleanup the value of the thread destroying this object
+        */
+       thread_cleanup_t destructor;
+
 };
 
 METHOD(thread_value_t, set, void,
@@ -50,11 +55,22 @@ METHOD(thread_value_t, get, void*,
 METHOD(thread_value_t, destroy, void,
        private_thread_value_t *this)
 {
+       void *val;
+
+       /* the destructor is not called automatically for the thread calling
+        * pthread_key_delete() */
+       if (this->destructor)
+       {
+               val = pthread_getspecific(this->key);
+               if (val)
+               {
+                       this->destructor(val);
+               }
+       }
        pthread_key_delete(this->key);
        free(this);
 }
 
-
 /**
  * Described in header.
  */
@@ -68,6 +84,7 @@ thread_value_t *thread_value_create(thread_cleanup_t destructor)
                        .get = _get,
                        .destroy = _destroy,
                },
+               .destructor = destructor,
        );
 
        pthread_key_create(&this->key, destructor);