Created
March 3, 2016 19:44
-
-
Save gsora/c10de3950ab0717bafdf to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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