golang – goroutine 死锁问题

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

golang - deadlock with gorutine

问题

下面的代码是将一个值放入通道中,并打印出与放入的值相同数量的值。我期望它能正常工作,但是出现了错误。

package main

import (
	"fmt"
	"time"
)

func main() {
	var ch chan int
	for i := 0; i < 3; i++ {
		go func(idx int) {
			ch <- (idx + 1) * 2
		}(i)
	}

	fmt.Println("result:", <-ch)
	fmt.Println("result:", <-ch)
	fmt.Println("result:", <-ch)
	//do other work
	time.Sleep(2 * time.Second)
}

在 playground 上进行了测试 - https://go.dev/play/p/FFmoSMheNfu

英文:

The code below is a code that puts a value into a channel and receives and print as much as you put in. I expected it to work, but an error occurs.

package main

import (
	&quot;fmt&quot;
	&quot;time&quot;
)

func main() {
	var ch chan int
	for i := 0; i &lt; 3; i++ {
		go func(idx int) {
			ch &lt;- (idx + 1) * 2
		}(i)
	}

	fmt.Println(&quot;result:&quot;, &lt;-ch)
	fmt.Println(&quot;result:&quot;, &lt;-ch)
	fmt.Println(&quot;result:&quot;, &lt;-ch)
	//do other work
	time.Sleep(2 * time.Second)
}

Tested on playground - https://go.dev/play/p/FFmoSMheNfu

答案1

得分: 3

你正在使用一个空通道。类型声明是不够的,你需要使用 make 来初始化通道。

ch := make(chan int)

https://go.dev/play/p/L1ewulPDYlS

有一集的 justforfunc 解释了空通道的行为以及它们为什么有时候很有用。

英文:

You are using a nil channel. The type declaration is not enough, you need to use make to initialize the channel.

ch := make(chan int)

https://go.dev/play/p/L1ewulPDYlS

There is an episode of justforfunc which explains how nil channels behave and why they are useful sometimes.

huangapple
  • 本文由 发表于 2022年2月14日 12:16:24
  • 转载请务必保留本文链接:https://go.coder-hub.com/71107115.html
匿名

发表评论

匿名网友

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

确定