+
+/*
+ * A function to destroy the TSD
+ */
+static void ctdl_thread_internal_dest_tsd(void *arg)
+{
+ if (arg != NULL) {
+ check_handles(arg);
+ free(arg);
+ }
+}
+
+
+/*
+ * A function to initialise the thread TSD
+ */
+void ctdl_thread_internal_init_tsd(void)
+{
+ int ret;
+
+ if ((ret = pthread_key_create(&ThreadKey, ctdl_thread_internal_dest_tsd))) {
+ lprintf(CTDL_EMERG, "pthread_key_create: %s\n",
+ strerror(ret));
+ exit(CTDLEXIT_DB);
+ }
+}
+
+/*
+ * Ensure that we have a key for thread-specific data.
+ *
+ * This should be called immediately after startup by any thread
+ *
+ */
+void CtdlThreadAllocTSD(void)
+{
+ ThreadTSD *tsd;
+
+ if (pthread_getspecific(ThreadKey) != NULL)
+ return;
+
+ tsd = malloc(sizeof(ThreadTSD));
+
+ tsd->tid = NULL;
+
+ memset(tsd->cursors, 0, sizeof tsd->cursors);
+ tsd->self = NULL;
+
+ pthread_setspecific(ThreadKey, tsd);
+}
+
+
+void ctdl_thread_internal_free_tsd(void)
+{
+ ctdl_thread_internal_dest_tsd(pthread_getspecific(ThreadKey));
+ pthread_setspecific(ThreadKey, NULL);
+}
+
+