From 5728e42634740463ba2da4758d817ad09a84dc60 Mon Sep 17 00:00:00 2001
From: wwylele <wwylele@gmail.com>
Date: Sat, 17 Dec 2016 13:08:38 +0200
Subject: [PATCH] Thread: remove the thread from the thread list when exiting

---
 src/core/hle/kernel/thread.cpp | 11 +++++++++--
 src/core/hle/kernel/thread.h   |  5 +++++
 src/core/hle/svc.cpp           |  2 +-
 3 files changed, 15 insertions(+), 3 deletions(-)

diff --git a/src/core/hle/kernel/thread.cpp b/src/core/hle/kernel/thread.cpp
index 4bbc08516..18b696f72 100644
--- a/src/core/hle/kernel/thread.cpp
+++ b/src/core/hle/kernel/thread.cpp
@@ -46,7 +46,7 @@ static std::vector<SharedPtr<Thread>> thread_list;
 // Lists only ready thread ids.
 static Common::ThreadQueueList<Thread*, THREADPRIO_LOWEST + 1> ready_queue;
 
-static Thread* current_thread;
+static SharedPtr<Thread> current_thread;
 
 // The first available thread id at startup
 static u32 next_thread_id;
@@ -63,7 +63,7 @@ Thread::Thread() {}
 Thread::~Thread() {}
 
 Thread* GetCurrentThread() {
-    return current_thread;
+    return current_thread.get();
 }
 
 /**
@@ -263,6 +263,13 @@ void WaitCurrentThread_ArbitrateAddress(VAddr wait_address) {
     thread->status = THREADSTATUS_WAIT_ARB;
 }
 
+void ExitCurrentThread() {
+    Thread* thread = GetCurrentThread();
+    thread->Stop();
+    thread_list.erase(std::remove(thread_list.begin(), thread_list.end(), thread),
+                      thread_list.end());
+}
+
 /**
  * Callback that will wake up the thread it was scheduled for
  * @param thread_handle The handle of the thread that's been awoken
diff --git a/src/core/hle/kernel/thread.h b/src/core/hle/kernel/thread.h
index 238359fc5..d4fefc573 100644
--- a/src/core/hle/kernel/thread.h
+++ b/src/core/hle/kernel/thread.h
@@ -252,6 +252,11 @@ void WaitCurrentThread_WaitSynchronization(std::vector<SharedPtr<WaitObject>> wa
  */
 void WaitCurrentThread_ArbitrateAddress(VAddr wait_address);
 
+/**
+ * Stops the current thread and removes it from the thread_list
+ */
+void ExitCurrentThread();
+
 /**
  * Initialize threading
  */
diff --git a/src/core/hle/svc.cpp b/src/core/hle/svc.cpp
index ef25acc4a..5839d7230 100644
--- a/src/core/hle/svc.cpp
+++ b/src/core/hle/svc.cpp
@@ -584,7 +584,7 @@ static ResultCode CreateThread(Handle* out_handle, s32 priority, u32 entry_point
 static void ExitThread() {
     LOG_TRACE(Kernel_SVC, "called, pc=0x%08X", Core::g_app_core->GetPC());
 
-    Kernel::GetCurrentThread()->Stop();
+    Kernel::ExitCurrentThread();
 }
 
 /// Gets the priority for the specified thread