原子性

分享
单例
package main

import (
	"fmt"
	"math/rand"
	"sync"
	"time"
)

type A struct {
	Item int
}

var a *A
var l sync.RWMutex

func GetGlobalA() *A {
	if a != nil {
		return a
	}

	l.Lock()
	if a == nil {
		rand.Seed(0)
		a = &A{Item: rand.Int()}
	}
	l.Unlock()
	return a
}

通常的单例是这么写的,实际上还有一种配合读写锁的写法(从nsq源码中学习到的)

	n.RLock()
	t, ok := n.topicMap[topicName]
	n.RUnlock()
	if ok {
		return t
	}

	n.Lock()

	t, ok = n.topicMap[topicName]
	if ok {
		n.Unlock()
		return t
	}

想到类似的场景再继续补坑吧