1 回答

TA貢獻(xiàn)1828條經(jīng)驗(yàn) 獲得超6個(gè)贊
在無(wú)緩沖通道的情況下(未指定大小時(shí)),它無(wú)法保存值,因?yàn)樗鼪](méi)有大小。因此,通過(guò)通道寫(xiě)入/傳輸數(shù)據(jù)時(shí)必須有讀取器在場(chǎng),否則將阻塞調(diào)用。
func main() {
? ? startDance := make(chan bool)
? ? startDance <- true
}
但是,當(dāng)您在上面的代碼中指定大?。ɡ?1)時(shí),就不會(huì)出現(xiàn)死鎖,因?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)制作它)。
- 1 回答
- 0 關(guān)注
- 146 瀏覽
添加回答
舉報(bào)