【发布时间】:2021-05-18 07:00:47
【问题描述】:
我正在使用缓冲通道,我得到了我需要的正确输出。
package main
import (
"fmt"
"sync"
)
var wg sync.WaitGroup
type Expert struct {
name string
age int
}
func main() {
fmt.Println("==== GoRoutines ====")
expertChannel := make(chan Expert, 3)
wg.Add(1)
go printHello()
wg.Add(1)
go addDataToChannel(expertChannel, "Name", 24)
wg.Add(1)
go addDataToChannel(expertChannel, "Name", 24)
wg.Add(1)
go addDataToChannel(expertChannel, "Name", 24)
wg.Wait()
close(expertChannel)
for x := range expertChannel {
fmt.Println("Expert Data :: ", x)
}
}
func printHello() {
for i := 1; i <= 5; i++ {
fmt.Println("This is from PrintHello() Function where i = ", i)
}
defer wg.Done()
}
func addDataToChannel(c chan Expert, name string, age int) {
defer wg.Done()
c <- Expert{
name,
age,
}
}
但是当我使用无缓冲通道时,我得到了错误,那就是 致命错误:所有 goroutine 都处于休眠状态 - 死锁! 为什么会发生这种情况以及如何解决?
package main
import (
"fmt"
"sync"
)
var wg sync.WaitGroup
type Expert struct {
name string
age int
}
func main() {
fmt.Println("==== GoRoutines ====")
expertChannel := make(chan Expert)
wg.Add(1)
go printHello()
wg.Add(1)
go addDataToChannel(expertChannel, "Name", 24)
wg.Add(1)
go addDataToChannel(expertChannel, "Name", 24)
wg.Add(1)
go addDataToChannel(expertChannel, "Name", 24)
wg.Wait()
close(expertChannel)
for x := range expertChannel {
fmt.Println("Expert Data :: ", x)
}
}
func printHello() {
for i := 1; i <= 5; i++ {
fmt.Println("This is from PrintHello() Function where i = ", i)
}
defer wg.Done()
}
func addDataToChannel(c chan Expert, name string, age int) {
defer wg.Done()
c <- Expert{
name,
age,
}
}
什么时候使用缓冲通道,什么时候使用非缓冲通道如何识别这两个通道类别的用例?
【问题讨论】:
标签: go concurrency