Call thread_attachThis() from your D shared library
Ali Çehreli
acehreli at yahoo.com
Sat Nov 18 00:23:31 UTC 2017
We had an issue today calling a D shared library from our Java code
where we were getting segfaults during GC collection cycles.
Of course we were being careful and calling Runtime.initialize() inside
our initialization function, which is called from the Java side:
extern (C) auto mylib_init() {
const rtInit = Runtime.initialize();
if (!rtInit) {
logf("Failed to initialize D runtime");
abort();
}
// ...
}
but we were forgetting about the fact that our API functions might be
called from threads other than the one that called Runtime.initialize().
extern (C) auto mylib_do_good_work() {
// Oops! A GC collection cycle may cause segmentation fault here
// ...
}
A simple solution is to call thread_attachThis() from each API function:
extern (C) auto mylib_do_good_work() {
import core.thread : thread_attachThis;
thread_attachThis();
// Now this thread is attached to D runtime and all is good
// ...
}
Although thread_attachThis() can be called multiple times from the same
thread, it may be possible to call it only once per thread if potential
calling threads are known; such threads can call a per-thread
initialization function on the D side. (We don't think our Java program
gives us that option because "our Java code" is a callback registered
with the framework of a Java program, which has total control of its
threads.)
Ali
More information about the Digitalmars-d-learn
mailing list