go - Channel中的一个数据被两个routine接收

标签 go channel goroutine

你好,我学习了围棋例程和 channel 。 我用 channel 做了一些实验,我通过 channel 发送数据并尝试在 2 个函数中捕获它。但是我的第二个函数没有运行

这是我的代码:

package main

import (
    "fmt"
    "os"
    "time"
)

func timeout(duration int, ch chan<- bool) {
    time.AfterFunc(time.Duration(duration)*time.Second, func() {
        ch <- true
    })
}

func watcher(duration int, ch <-chan bool) {
    <-ch
    fmt.Println("\nTimeout! no Answer after", duration, "seconds")
    os.Exit(0)
}

func watcher2(duration int, ch <-chan bool) {
    <-ch
    fmt.Println("This is watcher 2 as a second receiver")
}

func main() {
    var data = make(chan bool)
    var duration = 5

    go timeout(duration, data)
    go watcher(duration, data)
    go watcher2(duration, data)

    var input string
    fmt.Print("What is 725/25 ? ")
    fmt.Scan(&input)

    if input == "29" {
        fmt.Println("Correct")
    } else {
        fmt.Println("Wrong!")
    }
}

你能告诉我一些关于它的解释吗? 谢谢

最佳答案

正如@Andy Schweig 提到的,您只能从 Go channel 中拉取一次。如果你还想接收消息两次,你可以使用观察者设计模式:

import "fmt"

type Observer interface {
    Notify(message string)
}

type Watcher struct {
    name string
}

func (w Watcher) Notify(message string) {
    fmt.Printf("Watcher %s got message %s\n", w.name, message)
}

var watchers =  [...]Watcher {{name: "Watcher 1"}, {name: "Watcher 2"}}
var c = make(chan string)

func notifier() {

    var message string
    for {
        // Messaged pulled only once
        message = <- c

        // But all watchers still receive it
        for _, w := range watchers {
            w.Notify(message)
        }
    }
}

func main() {
    go notifier()

    c <- "hello"
    c <- "how are you?"
}

关于go - Channel中的一个数据被两个routine接收,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40325710/

相关文章:

go - 为什么 golang 选择 syscall 而不是 libc

go - 无法在 golang 中为 asn 解码定义正确的结构

go - 为什么 channel 的方向变化不能兼容?

matlab - Simulink 中的多 channel 音频输出

go - 当所有 worker 完成后关闭 channel

go - 如何使用 AWS SDK v2 在 dynamodb 中按键获取项目?

go - 如何使用 go-client 在 kubernetes 中获取 pod 的状态

go - 尝试使用 'range' 打印 channel 值后出现死锁

loops - 使用 goroutine 进行迭代会产生意想不到的结果

multithreading - Go 服务器在发送 INT 信号后挂起