1 回答

TA貢獻(xiàn)1798條經(jīng)驗(yàn) 獲得超7個(gè)贊
一個(gè)很好的使用方式WaitGroup是Add()在發(fā)送到頻道之前先調(diào)用,或者使用go關(guān)鍵字,Done()在從頻道接收后再調(diào)用。這樣Add(),無(wú)論是否在通道塊上發(fā)送,都可以確保始終按時(shí)調(diào)用。
我已經(jīng)更改了您的示例代碼來(lái)做到這一點(diǎn):
package main
import (
"fmt"
"sync"
)
type safeOperation struct {
i int
sync.Mutex
}
var wg sync.WaitGroup
func main() {
so := new(safeOperation)
ch := make(chan int)
for i := 0; i < 5; i++ {
wg.Add(1)
go so.Increment(ch)
wg.Add(1)
go so.Decrement(ch)
}
go func() {
for c := range ch {
fmt.Println("Receiving Channel Value: ", c)
wg.Done()
}
}()
wg.Wait()
//<-done
fmt.Println("Value: ", so.GetValue())
fmt.Println("Main method finished")
}
func (so *safeOperation) Increment(ch chan int) {
so.i++
ch <- so.i
}
func (so *safeOperation) Decrement(ch chan int) {
so.i--
ch <- so.i
}
func (so *safeOperation) GetValue() int {
so.Lock()
v := so.i
so.Unlock()
return v
}
當(dāng)然,您還希望safeOperation.i使用互斥鎖進(jìn)行保護(hù)(否則其值將是不可預(yù)測(cè)的),但這就是獲得所需輸出所必需的全部操作。
- 1 回答
- 0 關(guān)注
- 241 瀏覽
添加回答
舉報(bào)