[HOpenGL] HOpenGL and --enable-threaded-rts
Wolfgang Thaller
wolfgang.thaller@gmx.net
Tue, 18 Jun 2002 21:54:09 +0200
I have implemented a hack that makes HOpenGL work with
--enable-threaded-rts. It currently contains 3 lines of MacOS X-specific
code, and it needs cleaning up. More about that later.
> Simon and I don't understand GLUT's requirements at all clearly.
> Why is the context thread-local?
OpenGL is a state based API. All operations are defined in terms of how
they affect global state. All global state used by OpenGL is contained
in a so called "context". Every OpenGL command implicitly operates on a
"current context". If a program draws to two different windows, it uses
two different contexts.
In order to allow programs to use OpenGL draw into two different
contexts in two different threads, the "current context" pointer has to
be made thread-local. Most OpenGL implementations do this by now,
although there may be a few outdated ones left.
Context creation and management is _not_ part of the OpenGL standard.
There is a different API for every platform. GLUT is a cross-platform
"utility toolkit" for creating simple OpenGL applications. It is
supposed to isolate its user from all this context buisiness by always
setting up the correct context before calling back to the program. But
even if don't use GLUT, OpenGL requires the current context to be set
_in the current OS thread_ in order to operate.
We cannot rely on OpenGL implementations to use any known general
mechanism for thread-local storage.
Making OS threads correspond directly to Haskell threads is probably an
extensive change to the RTS that has lots of disadvantages.
My proposal is to leave dealing with thread-local state to the library
binding (in this case, HOpenGL). This requires just a little support
from the RTS. The library binding would have to include C-language
routines that get called by the RTS at certain points:
* when the RTS starts executing Haskell code in an OS thread
(grabCapability)
* when the RTS stops executing Haskell code in an OS thread
(releaseCapability)
* when the RTS is about to spawn a new thread in response to a callback
(scheduleThread_).
HOpenGL would just need to have about 3 platform-specific lines of code.
This would effectively make OpenGL's thread local state global again.
For real multithreaded use of OpenGL we would need some more RTS support.
We'd just need to agree on a nice little addition to the RTS API .
All libraries that currently can't be used because they rely on
thread-local state could then be made to work using a few lines of C
code.
The problems with recursive locks are, of course, not solved by this,
but I don't see a "perfect" all-round solution anywhere on the horizon.
(...and apart from that, I don't need recursive locks right now :-) )
Cheers,
Wolfgang