gpt4 book ai didi

Go:一个 channel 有多个听众

转载 作者:IT老高 更新时间:2023-10-28 13:10:08 24 4
gpt4 key购买 nike

如果主题错误,我很抱歉,但我希望你理解我的问题。我想通过 channel 将事件处理到不同的 goroutine。这是一些示例代码

type Event struct {
Host string
Command string
Output string
}


var (
incoming = make(chan Event)
)

func processEmail(ticker* time.Ticker) {
for {
select {
case t := <-ticker.C:
fmt.Println("Email Tick at", t)
case e := <-incoming:
fmt.Println("EMAIL GOT AN EVENT!")
fmt.Println(e)
}
}
}

func processPagerDuty(ticker* time.Ticker) {
for {
select {
case t := <-ticker.C:
fmt.Println("Pagerduty Tick at", t)
case e := <-incoming:
fmt.Println("PAGERDUTY GOT AN EVENT!")
fmt.Println(e)
}
}
}

func main() {

err := gcfg.ReadFileInto(&cfg, "dispatch-api.cfg")
if err != nil {
fmt.Printf("Error loading the config")
}

ticker := time.NewTicker(time.Second * 10)
go processEmail(ticker)

ticker := time.NewTicker(time.Second * 1)
go processPagerDuty(ticker)
}


func eventAdd(r render.Render, params martini.Params, req *http.Request) {

// create an event now
e := Event{Host: "web01-east.domain.com", Command: "foo", Output: "bar"}
incoming <- e
}

因此,股票代码事件只是创建而已。当我发出 API 调用来创建事件时,我只是从 processEmail 函数获得输出。它首先调用的任何 goroutine 都会通过 channel 获取事件。

有没有办法让这两个函数都获得该事件?

最佳答案

您可以使用 fan infan out(来自 Rob Pike 的演讲):

package main

func main() {
// feeders - feeder1, feeder2 and feeder3 are used to fan in
// data into one channel
go func() {
for {
select {
case v1 := <-feeder1:
mainChannel <- v1
case v2 := <-feeder2:
mainChannel <- v2
case v3 := <-feeder3:
mainChannel <- v3
}
}
}()

// dispatchers - not actually fan out rather dispatching data
go func() {
for {
v := <-mainChannel

// use this to prevent leaking goroutines
// (i.e. when one consumer got stuck)
done := make(chan bool)

go func() {
consumer1 <- v
done <- true
}()
go func() {
consumer2 <- v
done <- true
}()
go func() {
consumer3 <- v
done <- true
}()

<-done
<-done
<-done
}
}()

// or fan out (when processing the data by just one consumer is enough)
go func() {
for {
v := <-mainChannel
select {
case consumer1 <- v:
case consumer2 <- v:
case consumer3 <- v:
}
}
}()

// consumers(your logic)
go func() { <-consumer1 /* using the value */ }()
go func() { <-consumer2 /* using the value */ }()
go func() { <-consumer3 /* using the value */ }()
}

type payload int

var (
feeder1 = make(chan payload)
feeder2 = make(chan payload)
feeder3 = make(chan payload)

mainChannel = make(chan payload)

consumer1 = make(chan payload)
consumer2 = make(chan payload)
consumer3 = make(chan payload)
)

关于Go:一个 channel 有多个听众,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28527038/

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