英文:
go channel, seems all right, but it gets deadlock
问题
package main
import "fmt"
import "time"
func main() {
c := make(chan int)
c <- 42 // 向通道 c 写入数据
val := <-c // 从通道 c 读取数据
println(val)
}
我认为 c <- 42
是将 42 写入通道 c,然后 val := <-c
是将通道 c 中的值读取到 val 中。
但为什么会出现死锁呢?
英文:
package main
import "fmt"
import "time"
func main() {
c := make(chan int)
c <- 42 // write to a channel
val := <-c // read from a channel
println(val)
}
I think c <- 42
put 42 to channel c, then val := <-c
put value in c to val.
but why does it get deadlock?
答案1
得分: 5
你创建了一个非缓冲通道。因此,语句c <- 42
会阻塞,直到其他goroutine尝试从通道接收值。由于没有其他goroutine来执行接收操作,你遇到了死锁。有两种方法可以解决这个问题:
- 在一个不同的goroutine中执行接收操作。
- 给通道添加缓冲区。例如,
c := make(chan int, 1)
可以让你在通道上发送一个值而不会阻塞。
英文:
You have created an unbuffered channel. So the statement c <- 42
will block until some other goroutine tries to receive a value from the channel. Since no other goroutine is around to do this, you got a deadlock. There are two ways you could fix this:
- Perform the receive in a different goroutine.
- Add a buffer to the channel. For example,
c := make(chan int, 1)
would allow you to send a single value on the channel without blocking.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论