1 回答
TA贡献1828条经验 获得超6个赞
在无缓冲通道的情况下(未指定大小时),它无法保存值,因为它没有大小。因此,通过通道写入/传输数据时必须有读取器在场,否则将阻塞调用。
func main() {
startDance := make(chan bool)
startDance <- true
}
但是,当您在上面的代码中指定大小(例如 1)时,就不会出现死锁,因为它将有空间来保存数据。((https://robertbasic.com/blog/buffered-vs-unbuffered-channels-in-golang/)。)(https://www.golang-book.com/books/intro/10)你可以看看上述网站是为了更好地了解通道和并发性
package main
import (
"fmt"
"time"
)
func main() {
startDance := make(chan bool)
startSleep := make(chan bool)
forceSleep := make(chan bool)
go startDance1(startDance, forceSleep, startSleep)
go performSleep(startSleep, startDance)
startDance <- true
fmt.Println("now dance is started ")
forceSleep <- true
select {}
}
func startDance1(startDance chan bool, forceSleep chan bool, startSleep chan bool) {
fmt.Println("waiting to start dance")
select {
case <-startDance:
fmt.Println("staring dance")
}
for {
select {
case <-startDance:
fmt.Println("starting dance")
case <-forceSleep:
fmt.Println("aleardy dancing going to sleep")
select {
case startSleep <- true:
default:
}
default:
//this is just to show working this
// i added default or else this will go into deadlock
fmt.Println("dancing")
time.Sleep(time.Second * 1)
}
}
}
func performSleep(startSleep chan bool, startDance chan bool) {
select {
case <-startSleep:
fmt.Println("staring sleep")
}
fmt.Println("sleeping for 5 seconds ")
time.Sleep(time.Second * 5)
select {
case startDance <- true:
fmt.Println("started dance")
default:
fmt.Println("failed to start dance ")
}
}
上面的代码是对你的代码的一个小小的改进(我试图根据你的要求来制作它)。
- 1 回答
- 0 关注
- 104 浏览
添加回答
举报