我正在使用缓冲通道,我得到了我需要的正确输出。
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,
}
}
但是当我使用unBuffered通道时,我得到了错误,这是致命的错误:所有goroutines都睡着了 - 死锁!为什么会发生这种情况以及如何解决这个问题?
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,
}
}
我们什么时候会使用缓冲通道,什么时候会使用无缓冲通道 如何识别两个通道类别的用例?
皈依舞
相关分类