偶尔看到D语言有些代码里会出现 static this() {},如果是在类里好理解,静态构造函数。但是放到模块里,我就纳闷了,不知道具体起什么作用了。看了渡世白玉(http://www.dushibaiyu.com/)的代码,算是有点理解:
app.d
import std.stdio;
import std.concurrency;
import core.thread;
void fun()
{
writeln("fun run in thread :", Thread.getThis().id);
}
void spawnfun()
{
writeln("spawnfun run in thread :", Thread.getThis().id);
}
void main()
{
writeln("main in thread :", Thread.getThis().id);
spawn(&spawnfun);
auto th = new Thread(&fun);
th.start();
}
a.d
module a;
import core.thread;
import std.stdio;
static this()
{
writeln("A static this in thread :", Thread.getThis().id);
}
shared static this()
{
writeln("A shared static this in thread :", Thread.getThis().id);
}
运行结果如下:
官网解释如下:
https://dlang.org/spec/module.html
Static constructors are code that gets executed to initialize a module or a class before the main() function gets called. Static destructors are code that gets executed after the main() function returns, and are normally used for releasing system resources.
There can be multiple static constructors and static destructors within one module. The static constructors are run in lexical order, the static destructors are run in reverse lexical order.
Static constructors and static destructors run on thread local data, and are run whenever threads are created or destroyed.
Shared static constructors and shared static destructors are run on global shared data, and constructors are run once on program startup and destructors are run once on program termination.
具体应用场景还没想到,等有空了继续 学习,先忙工作了。