英文:
Why this channel operation will show dead lock error?
问题
package main
import "fmt"
var money int = 100
var update = make(chan int)
func updateM(count int) {
update <- count
}
func main() {
updateM(200)
fmt.Println(<-update)
}
但是当我在updateM(200)
前面加上go
关键字时,就没有错误了。
func main() {
go updateM(200)
fmt.Println(<-update)
}
有人可以告诉我,我是Go的新学习者。非常感谢。
英文:
package main
import "fmt"
var money int = 100
var update = make(chan int)
func updateM( count int) {
update<- count
}
func main() {
updateM(200)
fmt.Println(<-update)
}
but when i change the code to add a go in front of updateM(200)
then no error
func main() {
go updateM(200)
fmt.Println(<-update)
}
could anyone tell me , i am new learner of Go. Thanks a lot.
答案1
得分: 4
根据文档:
如果通道是无缓冲的,发送者会阻塞直到接收者接收到值。如果通道有缓冲区,发送者只会阻塞直到值被复制到缓冲区;如果缓冲区已满,这意味着等待直到某个接收者取走一个值。
你可以通过将通道的创建方式更改为
var update = make(chan int, 1)
来使其不阻塞,这样通道中就有一个空间可以存放一个元素。
英文:
From the documentation:
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.
You can make it not blocking by changing the channel creation to
var update = make(chan int, 1)
so that there's room for one item in the channel before it blocks.
答案2
得分: 2
一个写入未缓冲通道的操作会阻塞,直到有其他地方的代码读取该通道。在你的情况下,updateM
会无限期地被阻塞,因为它需要继续执行以便从通道中读取数据,但它无法读取通道中的数据。
通道用于协程之间的通信,对于自我通信来说是没有意义的。
英文:
A write to an unbuffered channel will block until there's someone reading it at the other end. In your case updateM
will block indefinitely because to continue, it needs to continue so that it can read from the channel, which it can't because it's not reading from the channel.
Channels are for communication between goroutines, they don't make sense for talking to yourself.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论