编程学习笔记之D语言(三)

偶尔看到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);
}

 

运行结果如下:164145_CAxi_214112.png

官网解释如下:
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.

具体应用场景还没想到,等有空了继续 学习,先忙工作了。

转载于:https://my.oschina.net/huanghongqiao/blog/689430

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值