Single-mode embodiment Golang

It applies only to single-threaded environment

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())
}

Support Concurrent Versions

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")
}

Optimization Concurrent Versions

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")
}

sync.Once version

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")
}

Guess you like

Origin www.cnblogs.com/daryl-blog/p/11369614.html