Skip to content

Commit

Permalink
Thread instantiation must happen via placement operations
Browse files Browse the repository at this point in the history
It's possible for the created thread to attempt to make use of m_thisThread before it's actually been moved out of the rvalue and into its permanent home.  To prevent this from happening, we completely avoid the earlier strategy of performing a move, and instead place the thread type in the memory allocated for it.  This happens before the corresponding thread is started.
  • Loading branch information
codemercenary committed Aug 15, 2014
1 parent bd55d63 commit 578f7b1
Show file tree
Hide file tree
Showing 2 changed files with 5 additions and 3 deletions.
6 changes: 4 additions & 2 deletions src/autowiring/BasicThread.cpp
Expand Up @@ -144,8 +144,10 @@ bool BasicThread::Start(std::shared_ptr<Object> outstanding) {
m_state->m_stateCondition.notify_all();
}

// Kick off a thread and return here
m_state->m_thisThread = std::thread(
// Place the new thread entity directly in the space where it goes to avoid
// any kind of races arising from asynchronous access to this space
m_state->m_thisThread.~thread();
new (&m_state->m_thisThread) std::thread(
[this, outstanding] () mutable {
this->DoRun(std::move(outstanding));
}
Expand Down
2 changes: 1 addition & 1 deletion src/autowiring/CoreThreadWin.cpp
Expand Up @@ -41,7 +41,7 @@ void SetThreadName(DWORD dwThreadID, LPCSTR szThreadName)
}

void BasicThread::SetCurrentThreadName(void) const {
DWORD threadId = ::GetThreadId(static_cast<HANDLE>(m_state->m_thisThread.native_handle()));
DWORD threadId = ::GetThreadId(m_state->m_thisThread.native_handle());
::SetThreadName(threadId, m_name);
}

Expand Down

0 comments on commit 578f7b1

Please sign in to comment.