Skip to content

Commit

Permalink
Native,Windows: Fix shutdown IoContext stuck bug
Browse files Browse the repository at this point in the history
Some threads were hanging on windows xp when the `IO::IoContext` was shutting down
  • Loading branch information
0blu committed Nov 12, 2024
1 parent 01bfa88 commit 1d64bc9
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 1 deletion.
1 change: 1 addition & 0 deletions src/shared/IO/Context/IoContext.h
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,7 @@ namespace IO
#if defined(WIN32)
explicit IoContext(HANDLE completionPort);
HANDLE m_completionPort;
volatile uint32_t m_runningThreadsCount;
#elif defined(__linux__)
IO::Native::FileHandle const m_epollDescriptor;
IO::Native::FileHandle const m_contextSwitchNotifyEventFd;
Expand Down
16 changes: 15 additions & 1 deletion src/shared/IO/Context/IoContext_windows.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ std::unique_ptr<IO::IoContext> IO::IoContext::CreateIoContext()
return std::unique_ptr<IoContext>(new IoContext(completionPort));
}

IO::IoContext::IoContext(HANDLE completionPort) : m_completionPort(completionPort), m_isRunning{true}
IO::IoContext::IoContext(HANDLE completionPort) : m_isRunning(true), m_completionPort(completionPort), m_runningThreadsCount(0)
{
}

Expand All @@ -35,6 +35,7 @@ void IO::IoContext::RunUntilShutdown()
DWORD bytesWritten = 0;
DWORD constexpr maxWait = INFINITE;

m_runningThreadsCount++;
while (m_isRunning)
{
bool isOkay = ::GetQueuedCompletionStatus(m_completionPort, &bytesWritten, &completionKey, reinterpret_cast<LPOVERLAPPED *>(&task), maxWait);
Expand All @@ -53,6 +54,7 @@ void IO::IoContext::RunUntilShutdown()
std::this_thread::yield(); // wait one os tick to try again
}
}
m_runningThreadsCount--;
}

bool IO::IoContext::IsRunning() const
Expand All @@ -64,7 +66,19 @@ void IO::IoContext::Shutdown()
{
if (m_isRunning)
{
uint32_t runningThreadsCountLocal = m_runningThreadsCount; // local count to prevent race condition after `running = false`
m_isRunning = false;

// We need to wake up the running threads by sending a "null-completion-event" and wait until all thread stopped
for (uint32_t i = 0; i < runningThreadsCountLocal; i++)
{
::PostQueuedCompletionStatus(m_completionPort, 0, 0, nullptr);
}
while (m_runningThreadsCount > 0)
{
std::this_thread::sleep_for(std::chrono::milliseconds(50));
}

::CloseHandle(m_completionPort);
m_completionPort = nullptr;
}
Expand Down

0 comments on commit 1d64bc9

Please sign in to comment.