gpt4 book ai didi

go - 没有任何 goroutine 但仍然得到 "all goroutines are asleep -deadlock"

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

我正在做一些实验。下面是我的代码。

package main

import (
"fmt"
"time"
)

func main(){
var a chan int
a = make(chan int)
for j:=0;j<10;j++{
firstRoutine(a, j)
time.Sleep(3 * time.Millisecond)
}
}

func firstRoutine(chennel chan int, j int){
i:=0
fmt.Println("j = ", j, "chennel = ", chennel)
chennel <- i
}

输出:
F:\Git\GitHub\GO\Prog\Concorrency>go run Channels.go
j = 0 chennel = <nil>
fatal error: all goroutines are asleep - deadlock!

goroutine 1 [chan send (nil chan)]:
main.firstRoutine(0x0, 0x0)
F:/Git/GitHub/GO/Prog/Concorrency/Channels.go:24 +0x11f
main.main()
F:/Git/GitHub/GO/Prog/Concorrency/Channels.go:14 +0x3f
exit status 2

我没有 gorutines在我的程序中,但仍然出现此错误。

下面的程序可以工作,至少没有 goroutine 错误。唯一的变化是 go firstRoutine(a, j)
package main

import (
"fmt"
"time"
)

func main(){

var a chan int
a = make(chan int)
for j:=0;j<10;j++{
go firstRoutine(a, j)
time.Sleep(3 * time.Millisecond)
}
}

func firstRoutine(chennel chan int, j int){
i:=0
fmt.Println("j = ", j, "chennel = ", chennel)
chennel <- i
}

输出:
F:\Git\GitHub\GO\Prog\Concorrency>go run Channels.go
j = 0 chennel = 0xc000048060
j = 1 chennel = 0xc000048060
j = 2 chennel = 0xc000048060
j = 3 chennel = 0xc000048060
j = 4 chennel = 0xc000048060
j = 5 chennel = 0xc000048060
j = 6 chennel = 0xc000048060
j = 7 chennel = 0xc000048060
j = 8 chennel = 0xc000048060
j = 9 chennel = 0xc000048060

最佳答案

您正在向 channel 写入/发送数据,但您没有从同一 channel 读取/接收数据。除非您从中读取/写入数据,否则对 channel 的写入/读取会阻塞。

编写一个从 channel a 读取数据的 for 循环或使用缓冲 channel

添加一些日志揭示了第二种情况。

在第二种情况下,您生成了 10 个单独的 go 例程,但由于从未从 channel a 读取数据,因此所有这些例程都被阻塞,并且在 10 次迭代后,for 循环退出,然后是 main 函数。

package main

import (
"fmt"
"time"
)

func main(){

var a chan int
a = make(chan int)
for j:=0;j<10;j++{
go firstRoutine(a, j)
fmt.Println("sleeping")
time.Sleep(3 * time.Millisecond)
fmt.Println("awake")
}
}

func firstRoutine(chennel chan int, j int){
i:=0
fmt.Println("j = ", j, "chennel = ", chennel)
chennel <- i
fmt.Println("pushed to channel"); // never gets printed
}

使用缓冲 channel 时:
package main

import (
"fmt"
"time"
)

func main(){

var a chan int
a = make(chan int, 11) // making a buffered channel of 11 elements
for j:=0;j<10;j++{
go firstRoutine(a, j)
fmt.Println("sleeping")
time.Sleep(3 * time.Millisecond)
fmt.Println("awake")
}
}

func firstRoutine(chennel chan int, j int){
i:=0
fmt.Println("j = ", j, "chennel = ", chennel)
chennel <- i
fmt.Println("pushed to channel"); // gets printed as buffer is bigger than the iterations, so no blocking
}

关于go - 没有任何 goroutine 但仍然得到 "all goroutines are asleep -deadlock",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58158087/

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