为什么这个通道操作会显示死锁错误?

huangapple go评论78阅读模式
英文:

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 &quot;fmt&quot;

var money int = 100
var update  = make(chan int) 

func updateM( count int)  {
	update&lt;- count
}

func main() {
	updateM(200)
	fmt.Println(&lt;-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(&lt;-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.

huangapple
  • 本文由 发表于 2017年3月22日 15:48:17
  • 转载请务必保留本文链接:https://go.coder-hub.com/42945587.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定