1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45

package main



import "fmt"



type Single struct {



}



var single *Single



func GetSingle() *Single {

    if single == nil {

        single = &Single{}

    }

    return single

}



func main() {

    fmt.Printf("%p\n", GetSingle())

    fmt.Printf("%p\n", GetSingle())

    fmt.Printf("%p\n", GetSingle())

}

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63

package main



import (

    "fmt"

    "sync"

    "time"

)



type Single2 struct {



}



var single2 *Single2

var lock *sync.Mutex = &sync.Mutex{}



func GetSingle2() *Single2 {

    lock.Lock()

    defer lock.Unlock()

    if single2 == nil {

        single2 = &Single2{}

    }

    return single2

}



func main() {

    go fmt.Printf("%p\n", GetSingle2())

    go fmt.Printf("%p\n", GetSingle2())

    go fmt.Printf("%p\n", GetSingle2())

    time.Sleep(time.Second)

    fmt.Println("done")

}

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67

package main



import (

    "fmt"

    "sync"

    "time"

)



type Single2 struct {



}



var single2 *Single2

var lock *sync.Mutex = &sync.Mutex{}



func GetSingle2() *Single2 {

    if single2 == nil {

        lock.Lock()

        defer lock.Unlock()

        if single2 == nil {

            single2 = &Single2{}

        }

    }

    return single2

}



func main() {

    go fmt.Printf("%p\n", GetSingle2())

    go fmt.Printf("%p\n", GetSingle2())

    go fmt.Printf("%p\n", GetSingle2())

    time.Sleep(time.Second)

    fmt.Println("done")

}

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59

package main



import (

    "fmt"

    "sync"

    "time"

)



type Single3 struct {



}



var once sync.Once

var single3 *Single3



func GetSingle3() *Single3 {

    once.Do(func() {

        single3 = &Single3{}

    })

    return single3

}



func main() {

    go fmt.Printf("%p\n", GetSingle3())

    go fmt.Printf("%p\n", GetSingle3())

    go fmt.Printf("%p\n", GetSingle3())

    time.Sleep(time.Second)

    fmt.Println("done")

}