D-Programming-Language/druntime — pull request #229 by alexrp (2012-05-28 23:27:37+00:00)
Title: Expose Thread.setThis().

This is probably going to be a bit controversial, but let me explain.

I have some code that helps my virtual machine deal with externally-created threads. Basically, it creates trampolines that take care of registering external threads with druntime as necessary. However, to handle thread detachment automagically, I have to use two hacks (one for Windows and another for POSIX). On Windows, I use the TLS callbacks (those that DLLs also get) to see when a thread is shutting down. On POSIX, I use a TLS key with a destructor function.

This scheme *almost* works fine. The problem is that by the time these cleanup routines are called, Thread.getThis() no longer returns a valid reference because the runtime thinks the thread is actually gone, which is of course not true (the dying thread calls the callback/destructor). Now, the cleanup routine I run in these TLS cleanup callbacks is actually a closure holding a reference to the original Thread object, meaning I can use Thread.setThis() to let the runtime know that there actually *is* a current thread, and thus be able to call rt_moduleTlsDtor() and thread_detachThis() as normal.

I know this may seem far-fetched, but I see basically no other way to do this with druntime's core.thread API. And I *need* to be able to do this, or I have to roll my own completely separate threading infrastructure, at which point using druntime at all becomes close to impossible.