gpt4 book ai didi

go - 使用 channel 时出现问题 : all goroutines are asleep - deadlock

转载 作者:行者123 更新时间:2023-12-01 22:33:28 28 4
gpt4 key购买 nike

我试图了解 channel 是如何运作的。我有这个例子:

import (
"fmt"
"runtime"
"time"
)

func greet(c chan string) {
fmt.Println("1: " + <-c)
fmt.Println("2: " + <-c)
}

func main() {
fmt.Println("main() started")

c := make(chan string, 1)

go greet(c)
c <- "John"

c <- "Mike"
c <- "Mary"
fmt.Println("active goroutines", runtime.NumGoroutine())
c <- "Edward"
time.Sleep(time.Second)
fmt.Println("main() stopped")
}
在执行上述代码时,我看到它给出了一个错误“ fatal error :所有 goroutines 都处于 sleep 状态 - 死锁!”。但据我了解,在将“Edward”发送到 channel 后,执行应该会被阻止。
c <- "Edward"
这个程序应该打印出 Mary 和 Edward 的值。我也不会在任何地方关闭这个 channel 。谁能告诉我为什么,我该如何解决这个问题?

最佳答案

请引用以下代码,以便您更好地理解它。我也添加了评论。虽然,@mkopriva 消除了您的疑虑,但我认为如果我发布评论代码会更好。

package main

import (
"fmt"
"time"
)

func greet(c chan string) {
// Range over the channel until close() is called
for r := range c {
// Print the names
fmt.Println(r)
}
}

func main() {
fmt.Println("main() started")
c := make(chan string, 1) // Make a bufferred channel with capacity of 1
go greet(c) // Spawn the goroutine
c <- "John" // Send
c <- "Mike" // Send
c <- "Mary" // Send
c <- "Edward" // Send
close(c) // Close the channel which signals the for loop
// inside greet to stop receiving
time.Sleep(2 * time.Second) // Let us give the main gorutine some time
// before it exits so that it lets the greet() to recieve all the names.
// But it's better to use sync.WaitGroup for this.
fmt.Println("main() stopped")
}

关于go - 使用 channel 时出现问题 : all goroutines are asleep - deadlock,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63761801/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com