From 1ab9e73d08a3d0f0fdb9069fb79876a9da722c3e Mon Sep 17 00:00:00 2001 From: Stephen Seo Date: Thu, 11 Jan 2024 19:18:12 +0900 Subject: [PATCH] Enforce thread-safety on destroy context --- src/UDPConnection.cpp | 17 ++++++++++++++--- 1 file changed, 14 insertions(+), 3 deletions(-) diff --git a/src/UDPConnection.cpp b/src/UDPConnection.cpp index 1c049b7..aa44fcd 100644 --- a/src/UDPConnection.cpp +++ b/src/UDPConnection.cpp @@ -2281,10 +2281,21 @@ int UDPC_is_valid_context(UDPC_HContext ctx) { void UDPC_destroy(UDPC_HContext ctx) { UDPC::Context *UDPC_ctx = UDPC::verifyContext(ctx); if(UDPC_ctx) { - // stop thread if threaded - if(UDPC_ctx->isAutoUpdating.load()) { + { + // Acquire lock so that this code does not run at the same time as + // enabling/disabling threaded-update. + std::lock_guard + setThreadedLock(UDPC_ctx->setThreadedUpdateMutex); + + // Stop thread if threaded. + // Set atomic bool to false always so that the thread will always + // stop at this point. UDPC_ctx->threadRunning.store(false); - UDPC_ctx->thread.join(); + if(UDPC_ctx->isAutoUpdating.load()) { + UDPC_ctx->thread.join(); + } + + // Drop lock at this point before destructing the context. } #if UDPC_PLATFORM == UDPC_PLATFORM_WINDOWS