簡體   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