Question: package main import ( fmt math / rand os strconv sync time ) func main ( ) {

package main
import (
"fmt"
"math/rand"
"os"
"strconv"
"sync"
"time"
)
func main(){
rand.Seed(time.Now().UnixNano())
if len(os.Args)<2{
fmt.Println("Please provide an integer argument.")
return
}
num, err := strconv.Atoi(os.Args[1])
if err != nil {
fmt.Println("Invalid input type.")
return
}
buffered := make(chan int, num)// buffered channel
var wait sync.WaitGroup
wait.Add(1)
go producer(&wait, buffered, num)
go consumer(buffered)
wait.Wait()
}
func producer(wait *sync.WaitGroup, out chan<- int, num int){
defer wait.Done()
for x :=0; x < num; x++{
value := rand.Intn(num)
fmt.Printf("Produced: %v
", value)
out <- value
}
close(out)
}
func consumer(in <-chan int){
for v := range in {
fmt.Printf("Consumed: %v
", v)
}
} simulate a producer and a consumer, each as a goroutine:
the producer produces a given number of random integers (in a given range), and sends each to the consumer via an unbuffered channel (unidirectional or bidirectional)
the producer goroutine outputs each number before it sends it
the consumer receives each integer from the producer and consumes it
the consumer goroutine outputs each number after it receives it
modify your program from part 1 so that a buffered channel of a given size is used This is part 2 of the program should have an output similar to Produced 1
Produced 4
Produced 0
Produced 1
Consumed 1
Consumed 4
Consumed 0
Consumed 1
Produced 4
Produced 7
Produced 0
Produced 8
Produced 9
Consumed 4
Consumed 7
Consumed 0
Consumed 8
Consumed 9
Produced 9

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!