WaitForSingleObject 总是在辅助线程中返回 WAIT_TIMEOUT

问题描述 投票:0回答:1

此问题发生在多线程应用程序(两个线程)中。 它似乎仅在 Windows 上以非常特定的配置发生 - 稍后会详细介绍。 该程序是用 C 语言编写的,并使用 pthreads 库。 它本质上是一个命令行解释器。

主线程生成一个“读取器”线程,该线程执行一个函数,该函数负责从标准输入中逐行读取用户输入文本并对读取的行进行排队。

主线程使该行出队,解释并执行相应的命令。

问题出在“读者”线程中。

HANDLE stdin_handle;
DWORD wait_result;

stdin_handle = GetStdHandle(STD_INPUT_HANDLE);
if (stdin_handle == INVALID_HANDLE_VALUE) {
  return ERROR_INVALID_HANDLE_VALUE;
}
if (stdin_handle == NULL) {
  return ERROR_NULL_HANDLE_VALUE;
}

do {
  wait_result = WaitForSingleObject(stdin_handle, 100);
  /* omitted: verify some condition here, break from loop if satisfied */
}
while(wait_result == WAIT_TIMEOUT);

当程序在某些特定配置中运行时,对

WaitForSingleObject
“reader”线程的调用始终返回
WAIT_TIMEOUT

出现问题的配置

  • 程序在 git bash 中运行,没有重定向(直接从键盘输入)

不出现问题的配置

  • 程序在 Windows 下的 git bash 中运行,标准输入从文件重定向
  • 程序在gdb中运行,无需重定向(直接从键盘输入)
  • 程序在CMD或Powershell中运行,无需重定向(直接从键盘输入)

我已阅读

synchapi.h
API 文档,但找不到解决此问题所需的信息。

c winapi io pthreads
1个回答
0
投票

这不是一个答案:只是将其作为我在评论中所说内容的示例发布。你能做这样的事吗?

#include <iostream>
#include <atomic>
#include <thread>
#include <chrono>
using namespace std::chrono_literals;

struct Info
{
    std::atomic<bool> running;
};

void one_seconder(Info* info)
{
    for (int ii = 0; info->running; ++ii)
    {
        std::cout << ii << std::endl;
        std::this_thread::sleep_for(1000ms);
    }
    std::cout << "Out of thread" << std::endl;
}
int main()
{
    Info info;
    char ch;

    // Start thread
    info.running = true;
    std::thread tobj(one_seconder, &info);

    std::cout << "Type any character and hit return" << std::endl;
    // Alternatively #include <conio.h> and use _getch();
    std::cin >> ch;
    info.running = false;
    std::cout << "Terminating" << std::endl;

    // Wait for thread to terminate
    tobj.join();

    std::cout << "Exit" << std::endl;
    return 0;
}
© www.soinside.com 2019 - 2024. All rights reserved.