簡體   English   中英

std :: thread和opengl應用程序中的std :: cin輸入

[英]std::thread and input with std::cin in an opengl application

我在OpenGL應用程序中使用線程來向用戶提供外殼。

我的問題是我無法在主循環末尾取消線程,因為std :: thread沒有提供取消方法,並且我的線程被std::cin >> var調用阻塞了,所以我可以不要使用布爾值來存儲線程應停止的事實。

我想知道是否有在線程(std :: thread)中使用std :: cin或其他解決方案的好方法。

您可能想要的是一個中斷線程,c ++不會給您一個線程,但是c ++並發實際上有一個簡單的實現。 那可能就是您所需要的。 如果boost也有一個,因為這本書是由線程庫的維護者編寫的,所以不會感到驚訝。

class interrupt_flag
    {
    public:
    void set();
        bool is_set() const;
    };
    thread_local interrupt_flag this_thread_interrupt_flag;
    class interruptible_thread
    {
        std::thread internal_thread;
        interrupt_flag* flag;
    public:
        template<typename FunctionType>
        interruptible_thread(FunctionType f)
        {
            std::promise<interrupt_flag*> p;
            internal_thread=std::thread([f,&p]{
                    p.set_value(&this_thread_interrupt_flag);
                    f(); 
                });
        flag=p.get_future().get();
    }
    void interrupt()
    {
        if(flag) {
            flag->set();
        }
    } 
};  

現在,您可以輕松地從主線程中取消線程。 我在書上放了一個鏈接,但書中的所有代碼也是免費的。 這是到書中源代碼的鏈接,盡管沒有這本書可能很難導航,這是一本很好的書,請注意。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM