我正在研究来自 https://talks.golang.org/2012/concurrency.slide#25 的“Go 并发模式” '
问题:
channel 如何从外部共享变量?在这种情况下,i 已被共享。 A点和B点的变量好像有什么特殊关系?这是什么?
这意味着什么?
对于我 := 0; ;我++
主要代码:
package main
import (
"fmt"
"math/rand"
"time"
)
func boring(msg string) <-chan string { // Returns receive-only channel of strings.
c := make(chan string)
go func() { // We launch the goroutine from inside the function.
for i := 0; ; i++ { // <--------- point B
c <- fmt.Sprintf("%s %d", msg, i)
time.Sleep(time.Duration(rand.Intn(1e3)) * time.Millisecond)
}
}()
return c // Return the channel to the caller.
}
func main() {
c := boring("boring!") // Function returning a channel.
for i := 0; i < 5; i++ { // <--------- point A
fmt.Printf("You say: %q\n", <-c)
}
fmt.Println("You're boring; I'm leaving.")
}
输出:
You say: "boring! 0"
You say: "boring! 1"
You say: "boring! 2"
You say: "boring! 3"
You say: "boring! 4"
You're boring; I'm leaving.
Program exited.
最佳答案
for (i := 0; ; i++) { }
创建一个永远递增的索引。
当您make(chan string )
时,您已经创建了一个读/写 channel 。您还可以在 go 函数中引用 channel 并将其作为返回值传递出去。 Go 对变量的使用方式进行了分析,称为“逃逸分析”,并选择是在堆上还是在堆栈上创建 channel ,在您的情况下是在堆上,这样当创建 channel 的函数退出时, channel 就不会得到释放。
关于go - 为什么 channel 不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26114209/