Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

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

Step: 1

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

Algorithmic Trading Navigating The Digital Frontier

Authors: Alex Thompson

1st Edition

B0CHXR6CXX, 979-8223284987

More Books

Students also viewed these Databases questions

Question

6. How do histories influence the process of identity formation?

Answered: 1 week ago