@@ -34,7 +34,9 @@ bool Thread::CreateThread(std::optional<dmq::Duration> watchdogTimeout)
3434{
3535 if (!m_thread)
3636 {
37+ m_threadStartPromise = std::promise<void >();
3738 m_threadStartFuture = m_threadStartPromise.get_future ();
39+ m_exit = false ;
3840
3941 m_thread = std::unique_ptr<std::thread>(new thread (&Thread::Process, this ));
4042
@@ -140,11 +142,24 @@ void Thread::ExitThread()
140142 m_exit.store (true );
141143 m_thread->join ();
142144
143- // Clear the queue if anything added while waiting for join
145+ // Prevent deadlock if ExitThread is called from within the thread itself
146+ if (m_thread->joinable ())
147+ {
148+ if (std::this_thread::get_id () != m_thread->get_id ())
149+ {
150+ m_thread->join ();
151+ }
152+ else
153+ {
154+ // We are killing ourselves. Detach so the thread object cleans up naturally.
155+ m_thread->detach ();
156+ }
157+ }
158+
144159 {
145160 lock_guard<mutex> lock (m_mutex);
146161 m_thread = nullptr ;
147- while (!m_queue.empty ())
162+ while (!m_queue.empty ())
148163 m_queue.pop ();
149164 }
150165
@@ -189,7 +204,7 @@ void Thread::WatchdogCheck()
189204 {
190205 LOG_ERROR (" Watchdog detected unresponsive thread: {}" , THREAD_NAME);
191206
192- // @TODO You can optionally trigger recovery, restart, or further actions here
207+ // @TODO Optionally trigger recovery, restart, or further actions here
193208 // For example, throw or notify external system
194209 }
195210}
@@ -235,6 +250,8 @@ void Thread::Process()
235250 {
236251 case MSG_DISPATCH_DELEGATE:
237252 {
253+ // @TODO: Update error handling below if necessary.
254+
238255 // Get pointer to DelegateMsg data from queue msg data
239256 auto delegateMsg = msg->GetData ();
240257 ASSERT_TRUE (delegateMsg);
0 commit comments