[英]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. 我在OpenGL应用程序中使用线程来向用户提供外壳。
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. 我的问题是我无法在主循环末尾取消线程,因为std :: thread没有提供取消方法,并且我的线程被
std::cin >> var
调用阻塞了,所以我可以不要使用布尔值来存储线程应停止的事实。
I would like to know if there is a good way of using std::cin in a thread (std::thread), or alternative solutions. 我想知道是否有在线程(std :: thread)中使用std :: cin或其他解决方案的好方法。
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. 您可能想要的是一个中断线程,c ++不会给您一个线程,但是c ++并发实际上有一个简单的实现。 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.
如果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();
}
}
};
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.
这是到书中源代码的链接,尽管没有这本书可能很难导航,这是一本很好的书,请注意。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.