为什么所有的goroutine都发生了死锁?

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

why are all goroutines deadlocked?

问题

我是你的中文翻译助手,以下是翻译好的内容:

我刚开始学习Go语言,也稍微看了一下关于"throw: all goroutines are asleep"的线程,但我仍然想知道为什么这段代码会出现死锁。我相信我在namesInDir中放入了一个数字,应该能够在之后打印出来。但似乎我无法将数字添加到通道中,这让我感到困惑。有人可以帮助我吗?

type uniprot struct {
	namesInDir chan int
}

func main() {
	u := uniprot{}
	u.namesInDir = make(chan int)
	u.namesInDir <- 1
	//u.readFilenames(os.Args[1])
	u.printName()
}

func (u *uniprot) printName() {
	name := <-u.namesInDir
	fmt.Println(name)
}

我得到了一些建议,说我可以通过给通道添加缓冲来解决问题。为什么这个方法不起作用呢?

u.namesInDir = make(chan int, 100)
u.namesInDir <- 1
for i := 0; i < 10; i++ {
	go u.printName()
}
英文:

I am new to Go and also looked abit on the thread "throw: all goroutines are asleep", but I am still wondering why this piece of code deadlock. I believe that I put a number in namesInDir, and should be able to print it afterwards. It seems that I can not add the number to the channel - which confuses me. Anyone that can help me?

type uniprot struct
{
	namesInDir chan int
}


func main(){
u := uniprot{}
u.namesInDir = make(chan int)
u.namesInDir &lt;- 1
//u.readFilenames(os.Args[1])
u.printName()
}	

func (u* uniprot) printName(){
	name := &lt;-u.namesInDir
	fmt.Println(name)
}

I got some suggestion and that I could cheat by buffering the channel. Why is not this working?

u.namesInDir = make(chan int, 100)
u.namesInDir &lt;- 1
for i := 0; i &lt; 10; i++ {
	go u.printName()
}

答案1

得分: 3

缓冲通道的工作方式如此

没有缓冲区的通道会阻塞发送者,直到接收者接收到值。在你的原始示例中,只有一个goroutine,因此当你发送整数时,所有的goroutine都会被阻塞。缓冲区可以解决这个问题。或者运行两个goroutine - 一个发送,一个接收。

package main

import "fmt"

type uniprot struct {
    namesInDir chan int
}

func (u *uniprot) printName() {
    name := <-u.namesInDir
    fmt.Println(name)
}

func main() {
    u := uniprot{}
    u.namesInDir = make(chan int, 1) // 在这里添加了缓冲区
    u.namesInDir <- 1
    //u.readFilenames(os.Args[1])
    u.printName()
}
英文:

Buffering the channel works like this.

A channel with no buffer blocks the sender until the receiver takes the value. In your original example you only have one go routine so all go routines are blocked when you send the integer. A buffer overcomes this. Alternatively run two go routines - one sending and one receiving.

package main

import &quot;fmt&quot;

type uniprot struct {
	namesInDir chan int
}

func (u *uniprot) printName() {
	name := &lt;-u.namesInDir
	fmt.Println(name)
}

func main() {
	u := uniprot{}
	u.namesInDir = make(chan int, 1) // Buffer added here
	u.namesInDir &lt;- 1
	//u.readFilenames(os.Args[1])
	u.printName()
}

huangapple
  • 本文由 发表于 2013年9月29日 01:04:23
  • 转载请务必保留本文链接:https://go.coder-hub.com/19069475.html
匿名

发表评论

匿名网友

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

确定