egl - Can context be shared between threads

Iceman picture Iceman · Jul 30, 2012 · Viewed 11.2k times · Source

Is it allowed to create egl context from main() and render from another thread, given the fact that the context handles are passed from main() to the thread's function?

Answer

Kenneth Hurley picture Kenneth Hurley · Aug 4, 2012

Yes, sure is.

First you need to create a context in in one thread:

   EGLint contextAttrs[] = {
     EGL_CONTEXT_CLIENT_VERSION, 2,
     EGL_NONE
};

LOG_INFO("creating context");
if (!(m_Context = eglCreateContext(m_Display, m_Config, 0, contextAttrs)))
{
    LOG_ERROR("eglCreateContext() returned error %d", eglGetError());
    return false;
}

Then in the other thread you create a shared context like this:

    EGLint contextAttrs[] =
    {
        EGL_CONTEXT_CLIENT_VERSION, 2,
        EGL_NONE
    };

    if (m_Context == 0)
    {
        LOG_ERROR("m_Context wasn't initialized for some reason");
    }

    // create a shared context for this thread
    m_LocalThreadContext = eglCreateContext(m_Display, m_Config, m_Context, contextAttrs);

You will of course have to have some mutex/semaphores to sync any updates you want to do with GLES. For instance you need to do a

eglMakeCurrent(m_Display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);

within the thread before the other thread can call

if (!eglMakeCurrent(m_Display, m_Surface, m_Surface, m_Context))
{
    LOG_ERROR("eglMakeCurrent() returned error %d", eglGetError());
}

Then you can create textures, load shaders, etc. from either thread