繁体   English   中英

如何在等待std :: cin时终止C ++ 11线程?

[英]How can I terminate a C++11 thread while it's waiting for std::cin?

我正在研究控制台IO的Console类(现在只是输入),我通过让后台线程不断检查输入来循环我的循环中的std::cin的输入。 然而,虽然它读取输入正常,但我(预期)遇到了一个问题,在我关闭我的主窗口(GLFW)之后,控制台窗口仍然在后台等待关闭或接收输入。 我正在寻找一种终止线程的方法,但找不到任何有关这种情况的好方法的信息。 有任何想法吗?

console.h

class Console
{
    public:
        Console();
        ~Console();

        bool isInputAvailable();
        std::string pullLastInput();

    private:
        bool do_quit;
        void thread_input();
        std::thread in_thread;
        std::queue<std::string> input_queue;
};

console.cpp:

Console::Console() : in_thread(&Console::thread_input, this)
{
    do_quit = false;
}

Console::~Console()
{
    do_quit = true;
    in_thread.join();
}

bool Console::isInputAvailable()
{
    return input_queue.size() > 0;
}

std::string Console::pullLastInput()
{
    std::string input;
    input = input_queue.front();
    input_queue.pop();

    return input;
}

void Console::thread_input()
{
    std::string input;
    while (!do_quit)
    {
        std::cin >> input;

        input_queue.push(input);
    }
}

在主窗口中,通过使用onClose事件或在析构函数中退出时,调用std::terminate或后台线程的析构函数。

这里解释了终止线程: 如何在C ++ 11中终止线程?

GLFW中关闭事件处理: http ://www.glfw.org/docs/latest/group__window.html#gaade9264e79fae52bdb78e2df11ee8d6a

没有办法可以轻松地做到这一点。

posix的快速解决方案涉及pthread_cancel 这将突然终止线程,泄漏终止线程当前持有的任何资源。

由于这个原因通常被认为是一种不好的做法,但在你的情况下,你将终止程序,所以它可能适合你。 考虑使用较低级别的I / O重新设计程序,以便您可以对用户输入执行超时等待。

在包含pthread.h之后,对代码的相关更改是:

Console::~Console()
{
     pthread_cancel( in_thread.native_handle() );
     in_thread.join();
}

//Get rid of the quit variable
void Console::thread_input()
{
     std::string input;
     while (true)
     {
        std::cin >> input;
        //Btw, you need a mutex here.
        input_queue.push(input);
     }
 }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM