How does D compare to Go when it comes to C interop?

Chris Wright via Digitalmars-d digitalmars-d at puremagic.com
Thu Dec 10 15:25:42 PST 2015


On Thu, 10 Dec 2015 20:17:57 +0000, Ola Fosheim Grøstad wrote:

> But the D fiber stacks aren't managed/safe, so in D the programmer is
> responsible for allocating a stack that is large enough. And that is
> neither safe or scalable.

Try it out!

---
import core.thread;

import std.stdio;

void main() {
	int i = 0;
	void f() { i++; }
	Fiber[] fibers;
	for (int j = 0; j < 1000; j++) {
		fibers ~= new Fiber(&f, 1_000_000_000);
	}
	foreach (fiber; fibers) {
		fiber.call;
	}
	writeln(i);
}
---

core.thread.Fiber is careful not to make any eager allocations. In most 
operating systems, you have to go through hoops to demand address space 
that's backed by memory *right now*. But instead of just not going 
through those hoops, Fiber is more explicit about asking for lazily 
filled address space.

On Posix, it will use mmap(2). mmap is specifically for reserving address 
space. Fiber passes flags for it to be backed by memory lazily (and zero-
initialized).

On Windows, it uses VirtualAlloc and passes MEM_RESERVE | MEM_COMMIT. The 
WinAPI docs say: "Actual physical pages are not allocated unless/until 
the virtual addresses are actually accessed."

druntime doesn't explicitly grow your stack because it's simply 
unnecessary. The OS's memory manager does it for you.

This doesn't work well for 32-bit processes because, while it doesn't 
demand memory up front, it does demand address space. But lazily 
demanding pages from the OS doesn't help. You still have to divide the 
address space among fiber stacks.


More information about the Digitalmars-d mailing list