std::thread and std::cin.get

std::thread and std::cin.get

本文关键字:std get cin thread and      更新时间:2023-10-16

我有一个全局变量名为DebugConsole。它使用Alloc console创建一个控制台,并重定向std::cout和std::cin。

问题是,当主机生成时,一切都很好。但是,当我使用std::cin.get()时,它会阻塞,并且应用程序的其余部分无法点击。所以我决定执行std::cin.get()。当你按下一个键时,控制台关闭得很好。当我取消复选框时,问题就出现了。线程无法连接,因为std::cin.get()阻止了它的移动。因此,我必须在它响应之前先输入。这将导致我的整个应用程序冻结。

我想让它,当你按下任何键,它退出我的控制台或当你取消复选框,它关闭我的控制台。

if (ButtonChecked)
{
    std::cout<<"To close this window: nRemove the checkmark from the Extract Box OR Press Any Key..n"<<std::flush;
    DebugConsole.StartThread([window]{  //create an std::thread and run the lambda in it.
        std::cin.get();
        DebugConsole.StopThread();  //join the thread.
        DebugConsole(false, false);  //close the console.
        UncheckBox(DebugBox);
    });
}
else
{
     DebugConsole.StopThread(); //basically just joins the thread..
     UncheckBox(DebugBox);
}

出现问题的代码在上面。知道我该怎么做吗?

主线程(在DebugConsole.StartThread()函数调用之后)应该与线程进行连接-当然,它需要知道线程ID,因此您可能需要threadid = DebugConsole.StartThread(...);才能使其工作。

我用GetAsyncKeyState(VK_RETURN) & 1代替std::cin.get()和std::cin.peek()来解决这个问题。

所有其他代码都很好。它只是cin。Get和peek不会停止阻挡。它正在阻止我的线程加入/分离,因为它一直在等待用户输入。