1.expvar(公共变量,原子操作)
var (
test = expvar.NewMap("Test")
testInt = expvar.NewInt("TestInt")
)
func init() {
test.Add("go", 10)
test.Add("go1", 10)
}
/*
http://localhost:8080/debug/vars
可查看全局信息
*/
func main() {
update()
sock, err := net.Listen("tcp", "localhost:8080")
if err != nil {
panic("error")
}
go func() {
http.Serve(sock, nil)
}()
select {}
}
func update() {
pubFloat := expvar.NewFloat("Float")
pubFloat.Set(66)
pubFloat.Add(0.1)
test.Set("go",pubFloat)
testInt.Set(66)
testInt.Add(2)
fmt.Println("int", testInt.String())
fmt.Println("go", test.String())
}
2.Cond(等待其他线程执行完)
/*
func NewCond(l Locker) *Cond 创建一个Cond
func (*Cond) Broadcast 唤醒所有等待的 Wait
func (*Cond) Signal 唤醒一个等待的wait
func (*Cond) Wait 进入锁定状态,等待释放
*/
func main() {
m := sync.Mutex{}
m.Lock()
c := sync.NewCond(&m)
go func() {
m.Lock()
defer m.Unlock()
fmt.Println("3. goroutine is owner of lock")
time.Sleep(2 * time.Second)
c.Broadcast() //唤醒所有等待的 Wait
fmt.Println("4. goroutine will release lock soon (deffered Unlock)")
}()
fmt.Println("1. main goroutine is owner of lock")
time.Sleep(1 * time.Second)
fmt.Println("2. main goroutine is still lockek")
c.Wait()
m.Unlock()
fmt.Println("Done")
}
3.map(线程安全的map)
/*
线程安全的map
Delete 删除
Load 读取
Range 遍历
Store 添加
*/
func main() {
var maph sync.Map
for i := 0; i < 3; i++ {
go func(i int) {
maph.Store(i, i)
}(i)
}
for i := 0; i < 10; i++ {
maph.Range(func(key, value interface{}) bool {
fmt.Printf("%d: %d\t", key, value)
return true
})
fmt.Println()
time.Sleep(time.Second)
}
v ,_ := maph.Load(2)
fmt.Println(v)
}
4.Once(多线程只允许调用一次)
/*
Once 的作用是多次调用但只执行一次
*/
func main() {
o := &sync.Once{}
go myfun(o)
go myfun(o)
time.Sleep(time.Second * 2)
}
func myfun(o *sync.Once) {
fmt.Println("Begin function")
o.Do(func() {
fmt.Println("Working...")
})
fmt.Println("Function end")
}
5.Pool(对象池)
/*
Pool 对象池
Get 获取一个对象
Put 添加一个对象
其他使用:开始生成10个对象
每次使用获取一个,使用完毕还回去
*/
func main() {
p := &sync.Pool{
New: func() interface{} {
return 0
},
}
a := p.Get().(int)
p.Put(100)
b := p.Get().(int)
fmt.Println(a, b)
}