From 7af4c018dc4bf6ec3d6e7e7abf87f4af821ab03f Mon Sep 17 00:00:00 2001
From: Marko Lindqvist <cazfi74@gmail.com>
Date: Thu, 29 May 2025 02:30:29 +0300
Subject: [PATCH 37/37] Add at_thread_exit callback support

Requested by Alina Lenk

See RM #600

Signed-off-by: Marko Lindqvist <cazfi74@gmail.com>
---
 utility/fcthread.c | 37 +++++++++++++++++++++++++++++++++++++
 utility/fcthread.h |  4 ++++
 2 files changed, 41 insertions(+)

diff --git a/utility/fcthread.c b/utility/fcthread.c
index 233c288307..fce484967f 100644
--- a/utility/fcthread.c
+++ b/utility/fcthread.c
@@ -22,6 +22,37 @@
 
 #include "fcthread.h"
 
+static at_thread_exit_cb *ate_cb = NULL;
+
+/*******************************************************************//**
+  Register callback to be called whenever a thread finishes.
+  This can be called only once. Latter calls will cause an error message
+  and return FALSE.
+***********************************************************************/
+bool register_at_thread_exit_callback(at_thread_exit_cb *cb)
+{
+  if (ate_cb != NULL) {
+    log_error("Trying to register multiple at_thread_exit callbacks.");
+    log_error("That's not supported yet.");
+
+    return FALSE;
+  }
+
+  ate_cb = cb;
+
+  return TRUE;
+}
+
+/*******************************************************************//**
+  Called at thread exit by all the thread implementations.
+***********************************************************************/
+static void at_thread_exit(void)
+{
+  if (ate_cb != NULL) {
+    ate_cb();
+  }
+}
+
 #ifdef FREECIV_C11_THR
 
 struct fc_thread_wrap_data {
@@ -41,6 +72,8 @@ static int fc_thread_wrapper(void *arg)
 
   free(data);
 
+  at_thread_exit();
+
   return EXIT_SUCCESS;
 }
 
@@ -172,6 +205,8 @@ static void *fc_thread_wrapper(void *arg)
 
   free(data);
 
+  at_thread_exit();
+
   return NULL;
 }
 
@@ -318,6 +353,8 @@ static DWORD WINAPI fc_thread_wrapper(LPVOID arg)
 
   free(data);
 
+  at_thread_exit();
+
   return 0;
 }
 
diff --git a/utility/fcthread.h b/utility/fcthread.h
index 54c31e0904..ccaa9c3a8e 100644
--- a/utility/fcthread.h
+++ b/utility/fcthread.h
@@ -86,6 +86,10 @@ void fc_thread_cond_signal(fc_thread_cond *cond);
 
 bool has_thread_cond_impl(void);
 
+typedef void (at_thread_exit_cb)(void);
+
+bool register_at_thread_exit_callback(at_thread_exit_cb *cb);
+
 #ifdef __cplusplus
 }
 #endif /* __cplusplus */
-- 
2.47.2

