英文:
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<-msg
is available chan send , but it cause deadlock!. thanks very much.
import "fmt"
func main() {
messages:=make(chan string)
//signals:=make(chan string)
select {
case msg:=<-messages:
fmt.Println(msg)
default:
fmt.Println("no mes receivedd")
}
msg:="h1"
select {
case messages<-msg:
fmt.Println("sent message",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中运行这段代码。
英文:
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 (
"fmt"
)
func main() {
messages := make(chan string)
//signals:=make(chan string)
msg := "h1"
go func(msg string) {
select {
case messages <- msg:
fmt.Println("sent message", msg)
}
}(msg)
select {
case msg := <-messages:
fmt.Println("Message recieved", msg)
}
}
<kbd>Playground</kbd>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论