Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
package main
import (
"fmt"
"math/rand"
"os"
"strconv"
"time"
)
const (
produceTime = 5
consumeTime = 2
simulationTime = 20
)
func producer(buff chan int) {
// constantly produce data
for {
// simulate work to produce data
time.Sleep(produceTime * time.Second)
// produce data (integer between 1 and 5)
data := rand.Intn(5) + 1
fmt.Printf("Produced data: %d\n", data)
// insert data into the buffer
buff <- data
}
}
func consumer(buff chan int) {
// constantly consume data
for {
// retrieve data
data := <-buff
// simulate work to consume data
time.Sleep(consumeTime * time.Second)
fmt.Printf("Consumed data: %d\n", data)
}
}
func main() {
// check arguments
args := os.Args
if len(args) != 4 {
fmt.Println("Usage:")
fmt.Printf("%s producers consumers buffer_capacity\n", args[0])
return
}
// seed rand with the current time
rand.Seed(time.Now().UTC().UnixNano())
// get number of producers
producers, err := strconv.Atoi(args[1])
if err != nil || producers < 1 {
producers = 1
}
// get number of consumers
consumers, err := strconv.Atoi(args[2])
if err != nil || consumers < 1 {
consumers = 1
}
// get buffer capacity
capacity, err := strconv.Atoi(args[3])
if err != nil || capacity < 1 {
capacity = 1
}
fmt.Printf("Producers: %d\n", producers)
fmt.Printf("Consumers: %d\n", consumers)
fmt.Printf("Capacity: %d\n", capacity)
buff := make(chan int, capacity)
for i := 0; i < producers; i++ {
go producer(buff)
}
for i := 0; i < consumers; i++ {
go consumer(buff)
}
// wait until simulation is over
time.Sleep(simulationTime * time.Second)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment