为什么这些 goroutine 处于休眠状态?

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

Why this goroutines are asleep?

问题

在我看来,“select...case”表示“如果有任何通道可用,则执行”。所以,为什么这里会出现错误呢?我认为message<-msg是可用的通道发送操作,但它导致了死锁。非常感谢。

package main

import "fmt"

func main() {
	messages := make(chan string)
	//signals := make(chan string)

	select {
	case msg := <-messages:
		fmt.Println(msg)
	default:
		fmt.Println("未收到消息")
	}

	msg := "h1"
	select {
	case messages <- msg:
		fmt.Println("发送消息", msg)
	}
}
英文:

In my opinion,the "select...case" means "If any chan is available, it executes".So,Why are there error here ,I think message&lt;-msg is available chan send , but it cause deadlock!. thanks very much.


import &quot;fmt&quot;

func main() {
	messages:=make(chan string)
	//signals:=make(chan string)

	select {
	case msg:=&lt;-messages:
		fmt.Println(msg)
	default:
		fmt.Println(&quot;no mes receivedd&quot;)
	}

	msg:=&quot;h1&quot;
	select {
	case messages&lt;-msg:
		fmt.Println(&quot;sent message&quot;,msg)
	}
}

答案1

得分: 1

第一个选择语句有一个default情况,所以它立即被选中。第二个选择语句试图写入messages,但没有其他goroutine在监听,所以你遇到了死锁。

将第二个选择语句移到第一个之前,在一个goroutine中执行,并移除default情况,这样你就可以成功发送/接收消息。

英文:

The first select has a default case, so it selected that immediately. The second select attempts to write to messages, but there are no other goroutines listening, so you have a deadlock.

Move the second select before the first, put it in a goroutine, and remove the default case, then you'll have a successful send/receive.

答案2

得分: 0

这是一个关于Go语言中通道(channel)的示例代码。代码中创建了两个goroutine,分别使用两个函数进行映射。一个goroutine与主函数进行映射,另一个与匿名函数进行映射。

package main

import (
	"fmt"
)

func main() {
	messages := make(chan string)
	//signals:=make(chan string)
	msg := "h1"
	go func(msg string) {
		select {
		case messages <- msg:
			fmt.Println("发送消息", msg)
		}
	}(msg)

	select {
	case msg := <-messages:
		fmt.Println("接收到消息", msg)
	}
}

你可以在Playground中运行这段代码。

英文:

为什么这些 goroutine 处于休眠状态?
source geeksforgeeks

> Here we have two goroutines map with two functions. one goroutine map
> with main function and one with an anonymous function.

package main

import (
	&quot;fmt&quot;
)

func main() {
	messages := make(chan string)
	//signals:=make(chan string)
	msg := &quot;h1&quot;
	go func(msg string) {
		select {
		case messages &lt;- msg:
			fmt.Println(&quot;sent message&quot;, msg)
		}
	}(msg)

	select {
	case msg := &lt;-messages:
		fmt.Println(&quot;Message recieved&quot;, msg)
	}
}

<kbd>Playground</kbd>

huangapple
  • 本文由 发表于 2021年12月10日 12:06:47
  • 转载请务必保留本文链接:https://go.coder-hub.com/70299655.html
匿名

发表评论

匿名网友

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

确定