From 7f963d1900e78b795545591c6a69b174f14fc6ea Mon Sep 17 00:00:00 2001 From: Maschell Date: Thu, 6 Oct 2022 11:55:58 +0200 Subject: [PATCH] Fix potential softlock that could happen if the thread was canceled but is not (marked as) terminated --- src/main.cpp | 21 +++++++++++---------- src/utils/CThread.h | 22 ++++++++++++++-------- 2 files changed, 25 insertions(+), 18 deletions(-) diff --git a/src/main.cpp b/src/main.cpp index 0142428..a922bf0 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -24,25 +24,26 @@ INITIALIZE_PLUGIN() { } } -void stopThread() { - if (thread != nullptr) { - delete thread; - thread = nullptr; - } -} - /* Entry point */ ON_APPLICATION_START() { initLogging(); - stopThread(); + + if (thread != nullptr) { + DEBUG_FUNCTION_LINE_WARN("The wiiload thread is still allocated but not running."); + thread->skipJoin = true; + delete thread; + thread = nullptr; + } DEBUG_FUNCTION_LINE("Start wiiload thread"); thread = new TcpReceiver(4299); } - ON_APPLICATION_REQUESTS_EXIT() { DEBUG_FUNCTION_LINE("Stop wiiload thread"); - stopThread(); + if (thread != nullptr) { + delete thread; + thread = nullptr; + } deinitLogging(); } \ No newline at end of file diff --git a/src/utils/CThread.h b/src/utils/CThread.h index 5cdc0da..cb5f3ae 100644 --- a/src/utils/CThread.h +++ b/src/utils/CThread.h @@ -100,17 +100,22 @@ public: //! Shutdown thread void shutdownThread() { - //! wait for thread to finish - if (pThread && !(iAttributes & eAttributeDetach)) { - if (!OSIsThreadTerminated(pThread)) { - if (isThreadSuspended()) { - resumeThread(); + if (skipJoin) { + DEBUG_FUNCTION_LINE_WARN("Skip joining the thread \"%s\", it's not running.", pThreadName.c_str()); + } else { + //! wait for thread to finish + if (!skipJoin && pThread && !(iAttributes & eAttributeDetach)) { + if (!OSIsThreadTerminated(pThread)) { + if (isThreadSuspended()) { + resumeThread(); + } + OSJoinThread(pThread, nullptr); + } else { + DEBUG_FUNCTION_LINE_WARN("Thread \"%s\" has already been terminated!!!", pThreadName.c_str()); } - OSJoinThread(pThread, nullptr); - } else { - DEBUG_FUNCTION_LINE_WARN("Thread \"%s\" has already been terminated!!!", pThreadName.c_str()); } } + //! free the thread stack buffer if (pThreadStack) { free(pThreadStack); @@ -132,6 +137,7 @@ public: eAttributeDetach = 0x08, eAttributePinnedAff = 0x10 }; + bool skipJoin = false; private: static int threadCallback(int argc, const char **argv) {