简体   繁体   中英

Using the same OpenGL context in multiple threads

I have a separate rendering thread where the renderer continiously iterates over a list of drawables like that (Java):

synchronized (renderingLock) {
  Iterator<DrawableObject> i = listOfDrawables.iterator();

  while (i.hasNext()) {
    draw(i.next());                          // OpenGL calls are inside
  }
}

Then, if at some point I need to change the list of drawables I start a new thread wich does something like this (simplified):

synchronized (renderingLock) {
  unloadFromVideoMemory(someUnusedDrawable); // OpenGL calls are inside
  loadIntoVideoMemory(newDrawable);          // OpenGL calls are inside

  listOfDrawables.add(newDrawable);
  listOfDrawables.remove(someUnusedDrawable);
}

But it's written in OpenGL wiki that:

In order for any OpenGL commands to work, a context must be current; all OpenGL commands affect the state of whichever context is current. The current context is a thread-local variable, so a single process can have several threads, each of which has its own current context. However, a single context cannot be current in multiple threads at the same time.

So is it safe to call the same OpenGL context from different threads, when the calls are synchronized? On Android (Java) this seems to work fine, but what about cross platform and/or native code? If I start making OpenGL calls in one thread and then continue to make them in a different thread, do I have to explicitly make the context current in this new thread?

Think about OpenGL as an UI thread.

All commands to OpenGL must be done on the OpenGL thread.

Moving to context, all commands to a OpenGL context must be done on the thread that was inited with that context.

Considering that you are using Java, there is a good chance that the native implementation does some sort of magic for you, so you are not actually calling the same context from different threads even thou it seems like it.

If you would actually use the same context on different threads, you will be in allot of trouble, synchronized or not :).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM