> ## Content Index
> Fetch the complete content index at: https://blog.hacking.pub/llms.txt
> Use this file to discover other available public pages before exploring further.

# 原子性
- URL: https://blog.hacking.pub/2019/05/16/yuan-zi-xing/
- Published: 2019-05-16T04:51:53.000Z
- Updated: 2019-05-16T04:51:53.000Z
- Author: chainhelen
- Tags: go, golang, go语言, 原子性, 单例

##### 单例

```
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
	}

```

#### 

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