在导入包的时候直接创建好对象,线程安全,但是会直接占用内存
hungry.go
package singleimport "sync"var h *hungryfunc init() {h = &hungry{}}type hungry struct {age intrwmux sync.RWMutex}func GetHungryInstance() *hungry {return h}func (h *hungry) IncrementAge() {h.rwmux.Lock()defer h.rwmux.Unlock()h.age++}func (h *hungry) GetAge() int {h.rwmux.RLock()h.rwmux.RUnlock()return h.age}
测试用例: hungry_test.go
package single
import (
"fmt"
"sync"
"testing"
)
func TestGetHungryInstance(t *testing.T) {
var wg sync.WaitGroup
wg.Add(20000)
for i := 0; i < 10000; i++ {
go func() {
defer wg.Done()
GetHungryInstance1()
}()
go func() {
defer wg.Done()
GetHungryInstance2()
}()
}
wg.Wait()
h := GetHungryInstance()
age := h.GetAge()
fmt.Printf("TestGetHungryInstance: %p\n", h)
fmt.Println("age: ", age)
}
func GetHungryInstance1() {
h := GetHungryInstance()
h.IncrementAge()
fmt.Printf("GetHungryInstance1: %p\n", h)
}
func GetHungryInstance2() {
h := GetHungryInstance()
h.IncrementAge()
fmt.Printf("GetHungryInstance2: %p\n", h)
}
