在导入包的时候直接创建好对象,线程安全,但是会直接占用内存

    hungry.go

    1. package single
    2. import "sync"
    3. var h *hungry
    4. func init() {
    5. h = &hungry{}
    6. }
    7. type hungry struct {
    8. age int
    9. rwmux sync.RWMutex
    10. }
    11. func GetHungryInstance() *hungry {
    12. return h
    13. }
    14. func (h *hungry) IncrementAge() {
    15. h.rwmux.Lock()
    16. defer h.rwmux.Unlock()
    17. h.age++
    18. }
    19. func (h *hungry) GetAge() int {
    20. h.rwmux.RLock()
    21. h.rwmux.RUnlock()
    22. return h.age
    23. }

    测试用例: 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)
    }