Skip to content

Instantly share code, notes, and snippets.

@gsora
Created March 3, 2016 19:44
Show Gist options
  • Select an option

  • Save gsora/c10de3950ab0717bafdf to your computer and use it in GitHub Desktop.

Select an option

Save gsora/c10de3950ab0717bafdf to your computer and use it in GitHub Desktop.
package main
import (
crypto "crypto/rand"
"fmt"
"math/big"
"runtime"
"time"
)
// ProducedData represents some data the producer function will output.
//
// Data: actual data produced
// ProducerID: id of the producer goroutine
type ProducedData struct {
Data int64
ProducerID int
}
func main() {
producer := make(chan ProducedData)
// spawn N producers, where N is the number of cpu cores
cpuCoresNumber := runtime.NumCPU()
fmt.Println("*** SPAWNING ", cpuCoresNumber, " GOROUTINES ***")
for i := 0; i < cpuCoresNumber; i++ {
go func(id int) {
for {
var bigN *big.Int
val := *big.NewInt(4)
bigN, _ = crypto.Int(crypto.Reader, &val)
time.Sleep(time.Duration(bigN.Int64()) * time.Second)
newN, _ := crypto.Int(crypto.Reader, &val)
kek := ProducedData{newN.Int64(), id}
producer <- kek
}
}(i)
}
// the consumer is the main itself
for {
select {
case got := <-producer:
fmt.Println("Producer ", got.ProducerID, " sent in something: ", got.Data)
case <-time.After(3 * time.Second):
fmt.Println("you're too slow, feed me faster!")
return
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment