Druntime and non-D threads

Ali Çehreli acehreli at yahoo.com
Tue Dec 12 00:41:52 UTC 2017


On 12/11/2017 08:58 AM, Mengu wrote:
 > On Monday, 11 December 2017 at 16:25:42 UTC, Ali Çehreli wrote:
 >> On 12/08/2017 02:54 AM, Nemanja Boric wrote:
 >>> [...]
 >>
 >> So, in cases where D is just a portable library, the only sane thing
 >> to do seems to be what Kagamin suggested: create a D thread and send
 >> requests to it.
 >>
 >> That way, we would be in total control of our threads, making
 >> entry-attach/exit-detach calls unnecessary. Agreed?
 >>
 >> Ali
 >
 > care to explain what exactly that means for the rest of us who are
 > n00bs? :-)

A recent issue made me spend quite a bit of time in core/thread.d, which 
improved my understanding of that code. As soon as I feel confident, I 
would like to write a document about my understanding. (Not necessarily 
thread.d's implementation but how to use D runtime with non-D threads.)

In the case of a D library that will be called by user threads with 
unknown attributes (e.g. some detachable threads some not; some joinable 
threads, some not), it's clear that a D function must attach and detach 
upon entry and exit to the API function:

// D library function, called on a non-D thread:
extern(C) void foo() {
     // Both of these calls involve locks:
     thread_attachThis();
     scope(exit) thread_detachThis();

     // Do D work by freely using the GC ...
}

We have to detach because we don't know whether we will ever be called 
from the same thread again or even whether the thread is about to 
terminate or not.

What Kagamin recommended is another way: Create threads in the D code, 
which obviates attach/detach calls and removes all questions about 
thread lifetimes. So, the API function could be the following:

void foo() @nogc {
     // Dispatch work to one of the D threads without doing
     // any complicated work here:
     enqueue_task();
}

Ali



More information about the Digitalmars-d mailing list