glGenTextures returns zero in background thread

霸气de小男生 提交于 2019-12-21 11:03:56

问题


I need to load textures in background thread in OpenGL ES. But glGenTextures always returns zero when called in background thread.

-(void) someMethodInMainThread {
   [self performSelectorInBackground:@selector(load) withObject:nil];
}

-(void) load {
   GLuint textureID = 0;
   glGenTextures(1, &textureID);        
}

textureID is zero. If i change code to [self performSelector:@selector(tmp) withObject:nil]; it will work correct and return 1. How should i load textures in background thread?


回答1:


This is a common error, each OpenGL context can be active (current) in one thread only, so when you create a new thread, it doesn't have any OpenGL context, and all GL calls fail.

Solution: Create another OpenGL context, make it current in your background thread. To load textures, you also want to share OpenGL names (texture ids, etc) with the main context.




回答2:


Use [EAGLContext setCurrentContext:] in your background thread before making calls to OpenGL.

An EAGLContext can only be the current context in a single thread. All OpenGL calls require a current context so this needs to be set from the background thread before calling any OpenGL function.

Be aware that EAGLContexts are not thread-safe.

From the Apple doc:

You should avoid making the same context current on multiple threads. OpenGL ES provides no thread safety, so if you want to use the same context on multiple threads, you must employ some form of thread synchronization to prevent simultaneous access to the same context from multiple threads.



来源:https://stackoverflow.com/questions/3467935/glgentextures-returns-zero-in-background-thread

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!