producer consumer - Conditional Go Routine/Channel -
i make statistics routine conditional runs on cases otherwise waste cycles half time. right have 1 go routine act producer feed 2 consumer routines via buffered channels. there way can make statistics routine conditional or there better pattern should follow? in advance , help!
func main() { options() go produce(readcsv(loc)) go process() go statistics() // on flag <-done } func produce(entries [][]string) { regex, err := regexp.compile(reg) if err != nil { log.error(reg + ", not valid regular expression") } else { _, each := range entries { if regex.matchstring(each[col]) { matches <- each stats <- each // on flag } } } done <- true } func process() { { match := <-matches if len(match) != 0 { // process } } } func statistics() { { stat := <-stats if len(stat) != 0 { // statistics } } }
there nothing wrong making conditional:
var stats chan []string // don't initialize stats. func main() { options() go produce(readcsv(loc)) go process() if flag { stats = make(chan []string, 1024) go statistics() // on flag } <-done } func produce(entries [][]string) { regex, err := regexp.compile(reg) if err != nil { log.error(reg + ", not valid regular expression") } else { _, each := range entries { if regex.matchstring(each[col]) { matches <- each if stats != nil { stats <- each // on flag } } } } close(done) } func process() { { select { case match := <-matches: if len(match) != 0 { // process } case <-done: return } } } func statistics() { { select { case stat := <-stats: if len(stat) != 0 { // statistics } case <-done: return } } }
Comments
Post a Comment