一、併發編程模板
func main() {
......
var wg sync.WaitGroup
wg.Add(1)
go func() {
defer wg.Done()
// to do
}()
wg.Add(1)
go func() {
defer wg.Done()
// todo
}()
wg.Wait()
}
二、鎖住共享資源
1. 原子函數
var counter int64 //多個goroutine都會增加其值的變量
//如果在goroutine中要對counter執行加法,那麼要用原子操作
atomic.AddInt64(&counter, 1) //對counter加1
另外兩個有用的原子函數是 LoadInt64 和 StoreInt64.
2. 互斥鎖
互斥鎖用於在代碼上創建一個臨界區,保證同一時間只有一個 goroutine 可以執行這個臨界區代碼。
var (
mutex sync.Mutex //定義一把互斥鎖
counter int //多個goroutine要操作的變量
)
mutex.Lock()
{
counter = 10
}
mutex.Unlock()
三、通道channel
當一個資源需要在 goroutine 之間共享時,通道在 goroutine 之間架起了一個管道,並提供了確保同步交換數據的機制。
1. 創建通道
//無緩衝的整形通道
unbufChan := make(chan int)
//有緩衝的字符串通道,通道大小是10個字符串
bufChan := make(chan string, 10)
2. 通道讀寫
bufChan := make(chan string, 10)
//向通道發送值
bufChan <- "hello"
//從通道取
value := <- bufChan
3. 無緩衝chan與有緩衝的區別
無緩衝chan是同步的,有緩衝chan是異步的。