Search code examples
androidopengl-esandroid-ndktextures

Can't call glGenTextures on multithreaded android app


I'm making an OpenGLES Android app using Android NDK, expanding from android's gljni example, which can be found here

It's using GLSurfaceView. Textures are initialized in a JNI function called from onSurfaceChanged() of GLSurfaceView.Renderer

When the user touches screen, the app needs more textures. In order to do so, glGenTextures() is called in a JNI function called in onTouchEvent().

The problem is that the thread id (which gettid() returns) seems completely arbitrary and not always the same to the thread id that has the OpenGL context.

It loads and shows up textures if the JNI function is called in the same thread, but fails if it's on another thread. So it's acting quite randomly.

Can I do something like :

  • share the OpenGL context so that I can call glGenTextures() successfully on any thread.

  • make onTouchEvent() to be called in only one thread that has the OpenGl Context

  • or anything that I can make it working

?

Thanks


Solution

  • It's not random behaviour, that's how OpenGL interacts with threads. A context is only current on only ONE thread, other threads don't have a GL context unless you specifically create a context for each thread you want to use with OpenGL. Without a context, all GL calls fail.