From 35b724c04a1f9c9581210d85d4f83ccd71035e47 Mon Sep 17 00:00:00 2001
From: Serge Petrenko <sergepetrenko@tarantool.org>
Date: Fri, 12 Aug 2022 11:56:38 +0300
Subject: [PATCH] core: introduce cord_exit() function

cord_exit should be always called in the exiting thread. It's a single
place to call all the thread-specific module deinitalization routines.

In-scope-of #4264

NO_DOC=refactoring
NO_TEST=refactoring
NO_CHANGELOG=refactoring
---
 src/lib/core/coio_task.c |  1 +
 src/lib/core/fiber.c     | 11 +++++++++++
 src/lib/core/fiber.h     |  7 +++++++
 3 files changed, 19 insertions(+)

diff --git a/src/lib/core/coio_task.c b/src/lib/core/coio_task.c
index bae6acc9e4..4dba16bc60 100644
--- a/src/lib/core/coio_task.c
+++ b/src/lib/core/coio_task.c
@@ -122,6 +122,7 @@ static int
 coio_on_stop(void *data)
 {
 	(void) data;
+	cord_exit(cord());
 	cord_destroy(cord());
 	free(cord());
 	return 0;
diff --git a/src/lib/core/fiber.c b/src/lib/core/fiber.c
index 37fda82c58..ca415678ac 100644
--- a/src/lib/core/fiber.c
+++ b/src/lib/core/fiber.c
@@ -1560,6 +1560,13 @@ cord_add_garbage(struct cord *cord, struct fiber *f)
 		cord->garbage = f;
 }
 
+void
+cord_exit(struct cord *cord)
+{
+	assert(cord == cord());
+	(void)cord;
+}
+
 void
 cord_destroy(struct cord *cord)
 {
@@ -1625,6 +1632,9 @@ void *cord_thread_func(void *p)
 	                                            CORD_ON_EXIT_WONT_RUN);
 	if (!changed)
 		handler->callback(handler->argument);
+
+	cord_exit(cord());
+
 	return res;
 }
 
@@ -1874,6 +1884,7 @@ fiber_init(int (*invoke)(fiber_func f, va_list ap))
 void
 fiber_free(void)
 {
+	cord_exit(&main_cord);
 	cord_destroy(&main_cord);
 }
 
diff --git a/src/lib/core/fiber.h b/src/lib/core/fiber.h
index 821376edf0..d9b2fb6ae0 100644
--- a/src/lib/core/fiber.h
+++ b/src/lib/core/fiber.h
@@ -771,6 +771,13 @@ extern __thread struct cord *cord_ptr;
 void
 cord_create(struct cord *cord, const char *name);
 
+/**
+ * Perform all the thread-specific deinitialization. Must be called in the
+ * exiting thread.
+ */
+void
+cord_exit(struct cord *cord);
+
 void
 cord_destroy(struct cord *cord);
 
-- 
GitLab