+#elif defined(CREATE_CLEANUP_THREAD)
+static void *
+cleanup_thread(void *arg)
+{
+ struct freeable_stack *freeable = arg;
+ pthread_t self = pthread_self();
+
+ FSHOW((stderr, "/cleaner thread(%p): joining %p\n",
+ self, freeable->os_thread));
+ gc_assert(pthread_join(freeable->os_thread, NULL) == 0);
+ FSHOW((stderr, "/cleaner thread(%p): free stack %p\n",
+ self, freeable->stack));
+ os_invalidate(freeable->stack, THREAD_STRUCT_SIZE);
+ free(freeable);
+
+ pthread_detach(self);
+
+ return NULL;
+}
+
+static void
+create_cleanup_thread(struct thread *thread_to_be_cleaned_up)
+{
+ pthread_t thread;
+ int result;
+
+ if (thread_to_be_cleaned_up) {
+ struct freeable_stack *freeable =
+ malloc(sizeof(struct freeable_stack));
+ gc_assert(freeable != NULL);
+ freeable->os_thread = thread_to_be_cleaned_up->os_thread;
+ freeable->stack =
+ (os_vm_address_t) thread_to_be_cleaned_up->control_stack_start;
+ result = pthread_create(&thread, NULL, cleanup_thread, freeable);
+ gc_assert(result == 0);
+ sched_yield();
+ }
+}
+