繁体   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