GlGenTextures returns zero in the background thread

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

-(void) someMethodInMainThread { [self performSelectorInBackground:@selector(load) withObject:nil]; } -(void) load { GLuint textureID = 0; glGenTextures(1, &textureID); } 

textureID is zero. If I changed the code to [self performSelector: @selector (tmp) withObject: nil]; it will work correctly and return 1. How to load textures into the background stream?

+6
multithreading iphone opengl-es
source share
2 answers

This is a common mistake, each OpenGL context can be active (current) in only one thread, so when creating a new thread it does not have any OpenGL context, and all GL calls are not made.

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

+9
source share

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

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

Remember that EAGLContexts are not thread safe.

From an Apple doc:

You should avoid using the same context in multiple threads. OpenGL ES does not provide thread safety, so if you want to use the same context for multiple threads, you should use some form of thread synchronization to prevent multiple threads from accessing the same context simultaneously.

-one
source share

All Articles