1 回答

TA貢獻(xiàn)1946條經(jīng)驗(yàn) 獲得超4個(gè)贊
在無(wú)緩沖通道的情況下(未指定大小時(shí))它不能保存一個(gè)值,因?yàn)樗鼪](méi)有大小。因此,在通過(guò)通道寫入/傳輸數(shù)據(jù)時(shí)必須有讀取器在場(chǎng),否則它將阻塞調(diào)用。
func main() {
startDance := make(chan bool)
startDance <- true
}
但是當(dāng)您在上面的代碼中指定一個(gè)大小(比如 1)時(shí),它不會(huì)是死鎖,因?yàn)樗鼘⒂锌臻g來(lái)保存數(shù)據(jù)。(((https://robertbasic.com/blog/buffered-vs-unbuffered-channels-in-golang/)。)(https://www.golang-book.com/books/intro/10)你可以看看上面的網(wǎng)站是為了更好地了解通道和并發(fā)
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 ")
}
}
上面的代碼是對(duì)你的一個(gè)小的改進(jìn)(我試圖根據(jù)你的要求來(lái)做)。我建議您閱讀一些書籍以了解有關(guān) Go 并發(fā)性的更多信息(https://www.golang-book.com/books/intro/10_
- 1 回答
- 0 關(guān)注
- 153 瀏覽
添加回答
舉報(bào)