gpt4 book ai didi

go - 另一个 golang 提出了关于理解它如何处理的问题

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

我正在浏览 blog post了解 channel ,我有一个关于 2nd example 的问题.我在操场上稍微修改了一下 this ,我在 channel 中放置更多项目,如下所示:

package main

import (
"fmt"
)

func main() {
n := 3
in := make(chan int)
out := make(chan int)

// We now supply 2 channels to the `multiplyByTwo` function
// One for sending data and one for receiving
go multiplyByTwo(in, out)

// We then send it data through the channel and wait for the result
in <- n
in <- 3
in <- 6
in <- 10
fmt.Println(<-out)
}

func multiplyByTwo(in <-chan int, out chan<- int) {
// This line is just to illustrate that there is code that is
// executed before we have to wait on the `in` channel
fmt.Println("Initializing goroutine...")

// The goroutine does not proceed until data is received on the `in` channel
num := <-in

// The rest is unchanged
result := num * 2
out <- result
}

但这会引发错误:
Initializing goroutine...
fatal error: all goroutines are asleep - deadlock!

goroutine 1 [chan send]:
main.main()
/tmp/sandbox639017164/prog.go:18 +0xe0

goroutine 6 [chan send]:
main.multiplyByTwo(0x430080, 0x4300c0)
/tmp/sandbox639017164/prog.go:34 +0xe0
created by main.main
/tmp/sandbox639017164/prog.go:14 +0xa0

我对此的解释是 channel 应该处理传入的数据,那么如果我只是简单地向 channel 添加更多内容,为什么会引发错误?我假设它也会传递其他数字并通过函数运行这些数字。

如果我在没有输出 channel 的情况下这样运行它:
package main

import (
"fmt"
)

func main() {
n := 3
in := make(chan int)
//out := make(chan int)

// We now supply 2 channels to the `multiplyByTwo` function
// One for sending data and one for receiving
go multiplyByTwo(in)

// We then send it data through the channel and wait for the result
in <- n
in <- 3
in <- 6
in <- 10
}

func multiplyByTwo(in <-chan int) {
// This line is just to illustrate that there is code that is
// executed before we have to wait on the `in` channel
fmt.Println("Initializing goroutine...")

// The goroutine does not proceed until data is received on the `in` channel
num := <-in

// The rest is unchanged
result := num * 2
fmt.Println(result)
}

它处理 channel 的第一个输入,但随后再次出错。 fatal error: all goroutines are asleep - deadlock!

最佳答案

goroutine 处理一个值,然后终止。您只能将第一个值发送到您的 goroutine,之后,goroutine 就消失了,并且没有任何东西在听您的 channel 。这就是为什么你会陷入僵局,你试图将数据发送到没有监听器的 channel 。

您的 channel 没有缓冲。这意味着,只有当至少有一个监听器从该 channel 读取数据并且其他一些 goroutine 写入该 channel 时,才会通过该 channel 进行数据交换。如果您创建缓冲 channel ,则可以继续添加它们,直到缓冲区已满。否则,要使写操作成功,必须有匹配的读操作。

这会起作用:

func multiplyByTwo(in <-chan int) {
for num:=range in {
// process num
}
// If here, then channel in is closed
}

in <- n
in <- 3
in <- 6
in <- 10
close(in)
// Wait for the goroutine to finish

关于go - 另一个 golang 提出了关于理解它如何处理的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58718552/

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