我正在尝试使用 Win32 API 创建一个从 STD_INPUT_HANDLE 读取的子线程,并将它读取的字节推送到套接字中。因为我希望能够在退出时安全地关闭此线程,所以我使用 ReadFileEx() 和重叠 I/O,而不是普通的旧阻塞 ReadFile()。这个想法是我的线程将在WaitForSingleObject()而不是ReadFile()中等待,当主线程希望从线程离开时,它会在该对象上发出信号,从线程将唤醒并退出,然后主线程可以继续其关闭序列。
我的问题是这样的:尽管文档说 ReadFileEx() 是异步的,因此永远不会阻塞……我的从属线程仍在 ReadFileEx() 中阻塞。(我在事件循环中插入了 printf 以验证它在哪里阻塞)因此,我的主线程无法关闭从属线程,因此主程序永远不会退出。
我做错了什么,还是 ReadFileEx() 意味着在从标准输入读取时阻塞?如果是后者,线程关闭问题的解决方案是什么?从属线程的入口函数如下,供大家参考...
[... in the main thread, before the slave thread is spawned...]
_stdinHandle = GetStdHandle(STD_INPUT_HANDLE);
_wakeupSignal = CreateEvent(0, false, false, 0);
[...]
VOID WINAPI CompletedReadRoutine(DWORD dwErr, DWORD cbBytesRead, LPOVERLAPPED lpOverLap)
{
printf("CompletedReadRoutine dwErr=%li cbBytesRead=%li overlap=%p\n", dwErr, cbBytesRead, lpOverLap);
}
void StdinDataIO :: IOThreadEntry()
{
char buf[4096];
OVERLAPPED olap;
bool keepGoing = true;
bool overlappedReadPending = false;
while(keepGoing)
{
if (overlappedReadPending)
{
DWORD waitResult = WaitForSingleObjectEx(_wakeupSignal, INFINITE, true);
switch(waitResult)
{
case WAIT_IO_COMPLETION:
{
overlappedReadPending = false;
DWORD numBytesRead;
if ((GetOverlappedResult(_stdinHandle, &olap, &numBytesRead, true) == false)||(SendData(_slaveSocket, buf, numBytesRead, true) != numBytesRead)) keepGoing = false;
}
break;
default:
keepGoing = false;
break;
}
}
else
{
memset(&olap, 0, sizeof(olap));
if (ReadFileEx(_stdinHandle, buf, sizeof(buf), &olap, CompletedReadRoutine)) overlappedReadPending = true;
else keepGoing = false;
}
}
if (overlappedReadPending) CancelIo(_stdinHandle);
_slaveSocket.Reset(); // this alerts the main thread that we are gone
}