Multiple threads and one context

I have an application which has a number of threads all working with the same context. Some threads create and stream video textures, some receive commands over network and deal with them and one is the main application calling other render commands and swapping.

Currently I am having a special class which lets threads aquire a context and later release it by using a mutex. This does sort of work, but it gives me quite a few locks here and there and I am tired of debugging it.

What would be “the right way” of dealing with this?

I see a few possible ways, none of which is truely like

1: wrap all opengl calls in methods which start with blocking on a mutex , aquiring a context and end by releasing it. Much like what I have now

2: invoke method calls on a single context owning thread which essentially makes the opengl part single threaded (ok, since I have no long running blocking opengl calls)

3: create a context for each thread and share their resources (textures). I have no experience with that.

Perhaps of some use to you:

Extension GL_ARB_sync (core feature of OpenGL>=3.2) provides
functionality to synchronize between multiple contexts.

ref: http://www.opengl.org/registry/specs/ARB/sync.txt
ref: OpenGL Spec 3.2, section 5.6 “Sync Objects and Fences”, page 360 and appendix D “Shared Objects and Multiple Contexts” page
465.

Method 3 is the way to go for OpenGL>=3.2.

Method 3 is also the way to for OpenGL<3.2. Similar to method 1, you would have some locking mechanism when you try to access resources (textures,…) but way less than by dealing with a single context. It will be only a “wait by necessity”.

ref “wait by necessity”:
http://archive.eiffel.com/doc/manuals/technology/concurrency/concurrency-06.html#HDR3

Option 3) is probably the best method, since it is the most “natual” way to do it in OpenGL. The other two methods are cumbersome and error prone. Also, with multiple contexts you only need mutexes were shared resources (textures,VBOs, etc) are concurrently accessed by the threads.

Thanks for al the advice. It seems the multiple context way is the one I should use. I neglected to provide a probably important detail though :-/ … some of the threads will be quite short lived. It will fit my design best if I can spawn worker threads dynamically, but I very much assume the overhead from creating a context for short lived threads is making this a bad idea.

I could then have a pool of pre-created contexts which are bound to the various worker threads, but would that not send me back to the context switching problems?