go - 为什么 channel 不起作用?

标签 go

我正在研究来自 https://talks.golang.org/2012/concurrency.slide#25 的“Go 并发模式” '

问题:

  1. channel 如何从外部共享变量?在这种情况下,i 已被共享。 A点和B点的变量好像有什么特殊关系?这是什么?

  2. 这意味着什么?

    对于我 := 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/

相关文章:

go - 在Golang中使用带有struct关键字的标签

go - 在 golang 中优化数据结构/字对齐填充

go - 请解释一下DEFER在golang中的行为

sql - 使用 Postgres 时为 "Operator does not exist: integer =?"

sql - 如何以一种好的方式使用 SQL NULL 值和 JSON?

networking - 使用 bufio.NewReader(conn) 阅读整条消息

regex - 使用正则表达式进行正则表达式

json - 是否可以在运行中即时转换 JSON 变量名?

arrays - 在 Go 中使用 slice 进行子集检查

go - 将字符串(键)映射到数字(或任何数据)