1 回答

TA贡献1798条经验 获得超7个赞
一个很好的使用方式WaitGroup是Add()在发送到频道之前先调用,或者使用go关键字,Done()在从频道接收后再调用。这样Add(),无论是否在通道块上发送,都可以确保始终按时调用。
我已经更改了您的示例代码来做到这一点:
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
}
当然,您还希望safeOperation.i使用互斥锁进行保护(否则其值将是不可预测的),但这就是获得所需输出所必需的全部操作。
- 1 回答
- 0 关注
- 211 浏览
添加回答
举报