Thursday, March 2, 2017

multiple goroutines reading a buffered channel

I wrote the following code to demonstrate multiple goroutines processing a single goroutine in response to a question from the Go Forum.

package main

import (
"fmt"
"time"
)

func main() {
queue := make(chan string, 10000)

// we can use a waitgroup but this works too
waitUntilDone := make(chan bool)

// input random data into the goroutine
go feedme(queue)

// we make sure to use our 4 core gigawatt cpu
// by spinning up 4 goroutines to process the incoming
// data in the `queue` goroutine
for i := 0; i < 4; i++ {
go func(queue chan string, i int) {
for {
data := <-queue
fmt.Printf("data received by goroutine %d!!: %s\n", i, data)
}
}(queue, i)
}

<-waitUntilDone
}

func feedme(q chan string) {
ticker := time.NewTicker(time.Millisecond * 250)
for t := range ticker.C {
q <- t.String()
}
}



No comments:

Post a Comment