- 通過go關鍵字開啟協(xié)程
func TestGoroutine(t *testing.T){
for i:=0 ; i< 5; i++ {
go (func(i int){
t.Log(i)
})(i)
}
t.Log("hello")
}
使用 go 關鍵字創(chuàng)建 goroutine 時,被調用函數(shù)的返回值會被忽略
- sync.WaitGroup
func TestGoroutine(t *testing.T){
var wg sync.WaitGroup
for i:=0 ; i< 5; i++ {
wg.Add(1)
go (func(i int){
defer wg.Done()
t.Log(i)
})(i)
}
wg.Wait()
t.Log("hello")
}
- 競態(tài)條件
func TestGoroutine(t *testing.T){
for i:=0 ; i< 5; i++ {
go (func(){
t.Log(i)
})()
}
t.Log("hello")
}
go run -race xxx.go 使用race參數(shù)可以檢測競態(tài)條件
- 加鎖 sync.Mutex
func TestGoroutine(t *testing.T){
var lock sync.Mutex
for i:=0 ; i< 5; i++ {
lock.Lock()
go (func(){
defer lock.Unlock()
t.Log(i)
})()
}
t.Log("hello")
}
在讀多寫少的環(huán)境中,可以優(yōu)先使用讀寫互斥鎖(sync.RWMutex),它比互斥鎖更加高效。sync 包中的 RWMutex 提供了讀寫互斥鎖的封裝
- atomic
- 調整并發(fā)性能
runtime.GOMAXPROCS(runtime.NumCPU())
thead vs groutine
- java thead stack 默認是1M
- groutine stack 初始化為 2k
groutime vs coroutine
- goroutine 可能發(fā)生并行執(zhí)行
- 但 coroutine 始終順序執(zhí)行
- groutime與coroutine區(qū)別