編程學習筆記之D語言(三)

偶爾看到D語言有些代碼裏會出現 static this() {},若是是在類裏好理解,靜態構造函數。可是放到模塊裏,我就納悶了,不知道具體起什麼做用了。看了渡世白玉(http://www.dushibaiyu.com/)的代碼,算是有點理解:
app.dhtml

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
 app

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.this

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.spa

Static constructors and static destructors run on thread local data, and are run whenever threads are created or destroyed.code

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.orm

具體應用場景還沒想到,等有空了繼續 學習,先忙工做了。htm

相關文章
相關標籤/搜索