D语言中的全局变量与多线程单例

        在D语言中的全局变量与其它语言有着一定的区别,D语言中的全部变量是分配在每一个线程中的,也就是说两个不同的线程访问到的全局变量是两个不同的数据。这是一个很神奇的事情,来看一个例子:

import std.stdio;
import core.thread;
import std.concurrency;
int temp = 0;
int main(string[] argv)
{
    spawn((){
        Thread.sleep(1.seconds);

        temp = 2;
        while(true)
        {
            writeln("in sub  thread : temp = ",temp,", temp address is ",&temp);
            Thread.sleep(1.seconds);
        }
    });

    temp = 1;
    while(true)
    {
        writeln("in main thread : temp = ",temp,", temp address is ",&temp);
        Thread.sleep(1.seconds);
    }
}

来看看运行结果是什么样子:

     image     运行的结果上可以看出:

     1. 两个线程中对temp没有内容覆盖问题

     2. 两个线程temp变量的地址不同

    也就是说这一个全部量变temp在不同的线程中却是不同的变量,这会有一个问题,那就是单例, 在其它程序中使用单例我们一个这么写:

class TestClass
{
    public static TestClass _Ins;    
    public static auto Ins()
    {
        if(_Ins is null)
            _Ins = new TestClass();
        return _Ins;
    }
}

      在D语言中,这个么也能运行,没有错误,但是结果却不是我们想要的,这是因为以上原因,这个单例会在每一个线程中创建一个,那就已经不是单例了,呵呵。应该叫做单线程单例。

      需要真正的使用多线程单例,我们需要使用__gshared关键字。如下:

class TestClass
{
    public __gshared static TestClass _Ins;    
    public static auto Ins()
    {
        if(_Ins is null)
            _Ins = new TestClass();
        return _Ins;
    }
}
原文地址:https://www.cnblogs.com/wanhongnan/p/5795500.html