androidopengl-esthread-safetykotlin-coroutinesdispatcher

Is it okay to run EGL commands on Dispatchers.Default in android?


As I understand, the EGL14.makeCurrent() function maps the thread to the EGLContext we created. And every EGL operations we execute will be executed on the EGLContext tied to the thread.

Is it safe to perform EGL operations wrapped with Dispatchers.Default? According to docs, ""Dispatchers.Default is backed by a shared pool of threads on JVM. By default, the maximum number of threads used by this dispatcher is equal to the number of CPU cores, but is at least two.""

So will my EGL operations switch thread in Dispatchers.Default and the EGLContext be unavailable for the thread I am in?


Solution

  • It's not safe to call EGL function from the same thread which was linked to a EGL context.

    You can create a dedicated thread to handle EGL calls and construct Dispatcher for them.

    Something like this:

    val dispatcher = Executors.newSingleThreadExecutor().asCoroutineDispatcher()
    
    suspend fun init() {
        withContext(dispatcher) {
            EGL14.makeCurrent() 
        }
    }
    
    suspend fun render() {
        withContext(dispatcher) {
            EGLFun()
        }
    }