gpt4 book ai didi

go - 在选择中未准备好向 channel 发送值

转载 作者:行者123 更新时间:2023-12-01 22:14:05 25 4
gpt4 key购买 nike

package main

import (
"fmt"
"time"
)

func main() {

ch := make(chan int)
go func() {
fmt.Printf("func at %d\n", time.Now().UnixNano())
select {
case ch <- 1:
fmt.Println("running send")
default:
fmt.Println("running default")
}
}()

time.Sleep(100 * time.Millisecond)
fmt.Printf("main at %d\n", time.Now().UnixNano())
fmt.Println(<-ch)
}

the playground here

我研究了一天但仍然无法解释为什么 case ch <- 1:没有准备好,默认情况下选择运行。当然,它会导致死锁!

最佳答案

来自 doc :

If the channel is unbuffered, the sender blocks until the receiver has received the value. If the channel has a buffer, the sender blocks only until the value has been copied to the buffer; if the buffer is full, this means waiting until some receiver has retrieved a value.



一种方法是使用它。这是接收器 goroutine 首先生成的。此外,如果接收器尚未准备好,则会选择默认情况。如果它准备好了,具体案例也将准备好。如果您多次运行此程序,您可以看到任何一种情况发生。

package main

import (
"fmt"
"time"
)

func main() {
ch := make(chan int)
// goroutine acts as the reciever
go func() {
fmt.Printf("main at %d\n", time.Now().UnixNano())
fmt.Println(<-ch)
}()
go func() {
fmt.Printf("func at %d\n", time.Now().UnixNano())
select {
case ch <- 1:
fmt.Println("running send")
default:
fmt.Println("running default")
}
}()
time.Sleep(1 * time.Second) // Wait for the goroutines
}


另一种解决方案是使用缓冲 channel :

package main

import (
"fmt"
"time"
)

func main() {

ch := make(chan int, 1)
go func() {
fmt.Printf("func at %d\n", time.Now().UnixNano())
select {
case ch <- 1:
fmt.Println("running send")
default:
fmt.Println("running default")
}
}()

time.Sleep(100 * time.Millisecond)
fmt.Printf("main at %d\n", time.Now().UnixNano())
fmt.Println(<-ch)
}

另外,请阅读本文 thread在堆栈溢出

关于go - 在选择中未准备好向 channel 发送值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61572444/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com