gpt4 book ai didi

Go: fatal error: all goroutines are sleep - 死锁

转载 作者:IT王子 更新时间:2023-10-29 01:52:41 25 4
gpt4 key购买 nike

我有一个文本文件,里面只有一行字。我想将所有这些单词单独存储在一个 channel 中,然后将它们从 channel 中提取出来并一个一个地打印出来。我有以下代码:

func main() {
f, _ := os.Open("D:\\input1.txt")
scanner := bufio.NewScanner(f)
file1chan := make(chan string)
for scanner.Scan() {
line := scanner.Text()

// Split the line on a space
parts := strings.Fields(line)

for i := range parts {
file1chan <- parts[i]
}
}
print(file1chan)
}

func print(in <-chan string) {
for str := range in {
fmt.Printf("%s\n", str)
}
}

但是当我运行它时,出现以下错误:

fatal error: all goroutines are asleep - deadlock!

goroutine 1 [chan send]: main.main()

我尝试在网上查找它,但我仍然无法修复它。谁能告诉我为什么会这样,我该如何解决?

谢谢!

最佳答案

您的 file1chan 是无缓冲的,因此当您尝试通过该 channel 发送一个值时,它会永远阻塞,等待某人获取一个值。

您需要启动一个新的 goroutine,或者使 channel 缓冲并将其用作数组。这是带有另一个 goroutine 的版本:

func main() {
f, _ := os.Open("D:\\input1.txt")
scanner := bufio.NewScanner(f)
file1chan := make(chan string)
go func() { // start a new goroutine that sends strings down file1chan
for scanner.Scan() {
line := scanner.Text()

// Split the line on a space
parts := strings.Fields(line)

for i := range parts {
file1chan <- parts[i]
}
}
close(file1chan)
}()
print(file1chan) // read strings from file1chan
}

func print(in <-chan string) {
for str := range in {
fmt.Printf("%s\n", str)
}
}

这里是缓冲版本,只处理一个字符串:

func main() {
f, _ := os.Open("D:\\input1.txt")
scanner := bufio.NewScanner(f)
file1chan := make(chan string, 1) // buffer size of one
for scanner.Scan() {
line := scanner.Text()

// Split the line on a space
parts := strings.Fields(line)

for i := range parts {
file1chan <- parts[i]
}
}
close(file1chan) // we're done sending to this channel now, so we close it.
print(file1chan)
}

func print(in <-chan string) {
for str := range in { // read all values until channel gets closed
fmt.Printf("%s\n", str)
}
}

关于Go: fatal error: all goroutines are sleep - 死锁,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36505012/

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