Use TLS to store the current thread.
This commit is contained in:
parent
7e88e54cbe
commit
3678a22c90
|
@ -345,7 +345,7 @@ class Thread : public WaitHandle {
|
||||||
// within that thread.
|
// within that thread.
|
||||||
static std::unique_ptr<Thread> Create(CreationParameters params,
|
static std::unique_ptr<Thread> Create(CreationParameters params,
|
||||||
std::function<void()> start_routine);
|
std::function<void()> start_routine);
|
||||||
static std::unique_ptr<Thread> GetCurrentThread();
|
static Thread* GetCurrentThread();
|
||||||
|
|
||||||
// Ends the calling thread.
|
// Ends the calling thread.
|
||||||
// No destructors are called, and this function does not return.
|
// No destructors are called, and this function does not return.
|
||||||
|
|
|
@ -426,10 +426,14 @@ class Win32Thread : public Win32Handle<Thread> {
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
thread_local std::unique_ptr<Win32Thread> current_thread_ = nullptr;
|
||||||
|
|
||||||
struct ThreadStartData {
|
struct ThreadStartData {
|
||||||
std::function<void()> start_routine;
|
std::function<void()> start_routine;
|
||||||
};
|
};
|
||||||
DWORD WINAPI ThreadStartRoutine(LPVOID parameter) {
|
DWORD WINAPI ThreadStartRoutine(LPVOID parameter) {
|
||||||
|
current_thread_ = std::make_unique<Win32Thread>(::GetCurrentThread());
|
||||||
|
|
||||||
auto start_data = reinterpret_cast<ThreadStartData*>(parameter);
|
auto start_data = reinterpret_cast<ThreadStartData*>(parameter);
|
||||||
start_data->start_routine();
|
start_data->start_routine();
|
||||||
delete start_data;
|
delete start_data;
|
||||||
|
@ -449,17 +453,22 @@ std::unique_ptr<Thread> Thread::Create(CreationParameters params,
|
||||||
delete start_data;
|
delete start_data;
|
||||||
return nullptr;
|
return nullptr;
|
||||||
}
|
}
|
||||||
GetThreadId(handle);
|
|
||||||
return std::make_unique<Win32Thread>(handle);
|
return std::make_unique<Win32Thread>(handle);
|
||||||
}
|
}
|
||||||
|
|
||||||
std::unique_ptr<Thread> Thread::GetCurrentThread() {
|
Thread* Thread::GetCurrentThread() {
|
||||||
|
if (current_thread_) {
|
||||||
|
return current_thread_.get();
|
||||||
|
}
|
||||||
|
|
||||||
HANDLE handle = ::GetCurrentThread();
|
HANDLE handle = ::GetCurrentThread();
|
||||||
if (handle == INVALID_HANDLE_VALUE) {
|
if (handle == INVALID_HANDLE_VALUE) {
|
||||||
return nullptr;
|
return nullptr;
|
||||||
}
|
}
|
||||||
|
|
||||||
return std::make_unique<Win32Thread>(handle);
|
current_thread_ = std::make_unique<Win32Thread>(handle);
|
||||||
|
return current_thread_.get();
|
||||||
}
|
}
|
||||||
|
|
||||||
void Thread::Exit(int exit_code) { ExitThread(exit_code); }
|
void Thread::Exit(int exit_code) { ExitThread(exit_code); }
|
||||||
|
|
Loading…
Reference in New Issue