![](/img/trans.png)
[英]Do C++11 threads provide a way for detached threads to continue after the main thread exits?
[英]C++11 threads, run on main thread
我正在尝试使用C ++ 11线程进行一些开发。 我想在异步线程中运行一些代码,当该代码完成后,我想在主线程上运行其他代码, 但是只有在完成后才可以!
这是因为我想异步运行的东西正在加载OpenGL内容,并且在执行线程时使用OpenGL上下文有点棘手,据我所知,在不同的线程中不要运行相同的上下文。
但是,我想创建一个加载程序线程,用于加载collada文件,这里耗时的东西实际上是解析文件并设置数据,而我可以(技术上)在单独的线程中完成所有操作,然后执行opengl在主线程上的特定任务。 (这是我最初的想法,我可能会以错误的方式进行操作)。
因此,我在想,如果我可以分离一个异步线程来加载collada文件并填充数据,那么一旦完成,我将在主线程上调用以绑定缓冲区,设置着色器等。 我可以在不使用线程的情况下完成此操作,但是在后台加载新数据而不会导致GL异常运行会非常顺利。
因此,我将尝试整理我想做的步骤:
我确实将所有这些工作同步进行,一旦分离的异步线程完成,我想要的是一种做一些事情的方式。
任何想法或对我的思想的建设性批评:P都受到热烈欢迎! 我可能会以错误的方式思考它,我一直在考虑做类似观察者模式的事情,但是我真的不知道如何以最佳方式解决它。 我不介意将OpenGL东西穿线,但似乎有点像自找麻烦。
如果我正确理解了您的用例,那么我认为以std::launch::async
策略开始的std::async()
函数可以确保操作确实在另一个线程上启动,它可以满足您的要求:
// Your function to be executed asynchronously
bool load_meshes();
// You can provide additional arguments if load_meshes accepts arguments
auto f = std::async(std::launch::async, load_meshes);
// Here, the main thread can just do what it has to do...
// ...and when it's finished, it synchronizes with the operation
// and retrieve its result (if any)
bool res = f.get(); // res will hold the return value of load_meshes,
// or this will throw an exception if one was
// thrown inside load_meshes()
if (res)
{
// ... and then it will go on doing the remaining stuff on the main thread
}
这里要注意的一件棘手的事情是,您应该始终将std::async()
的返回值分配给某个变量(类型为std::future<T>
),其中T
是load_meshes()
返回的类型。 。 否则,主线程将等待直到load_meshes()
完成(因此,就好像该函数在主线程中被调用一样)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.