简体   繁体   中英

std::thread and input with std::cin in an opengl application

I use a thread in order to provide a shell to user, in an OpenGL application.

My problem is that I can't cancel the thread at the end of my mainloop, because std::thread doesn't provide a cancel method, and my thread is blocked with a std::cin >> var call, so I can't use a boolean to store the fact that the thread should stop.

I would like to know if there is a good way of using std::cin in a thread (std::thread), or alternative solutions.

What you might want is an interrupting thread, c++ doesn't give you one but c++ concurrency in action has a simple implementation of one. That might be what you need. Wouldn't be surprised if boost also has one since the book is written by the maintainer of the thread library.

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();
        }
    } 
};  

Now you can easily cancel the thread from your main. I put a link to the book but all the code from the book is also online for free. Here is a link to the source code in the book, though it may be hard to navigate without the book, which is a great read BTW.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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