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 關注
- 149 瀏覽
添加回答
舉報