1 回答

TA貢獻1946條經驗 獲得超4個贊
在無緩沖通道的情況下(未指定大小時)它不能保存一個值,因為它沒有大小。因此,在通過通道寫入/傳輸數據時必須有讀取器在場,否則它將阻塞調用。
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 ")
}
}
上面的代碼是對你的一個小的改進(我試圖根據你的要求來做)。我建議您閱讀一些書籍以了解有關 Go 并發性的更多信息(https://www.golang-book.com/books/intro/10_
- 1 回答
- 0 關注
- 157 瀏覽
添加回答
舉報