Skip to content

Instantly share code, notes, and snippets.

@yashtibrewal
Created May 25, 2022 09:45
Show Gist options
  • Save yashtibrewal/2d86f2adc7e50aaa89fa8365b3b082c5 to your computer and use it in GitHub Desktop.
Save yashtibrewal/2d86f2adc7e50aaa89fa8365b3b082c5 to your computer and use it in GitHub Desktop.
Channels Alternative Solution (ZTM)
//--Summary:
// Create a program that utilizes goroutines to run the provided calculation
// function on a number of jobs. The results from the goroutines must be
// communicated back to the main thread using a channel, and then added
// together.
// Create reciever and send back
//--Requirements:
//* Run `longCalculation` for each job generated by the `makeJobs` function
//* Each job must be run in a separate goroutine
//* The result from `longCalculation` must be provided to the main function
// using a channel
//* Sum the results from each job to generate a final result, and print it
// to the terminal
package main
import (
"fmt"
"math/rand"
"time"
)
type Job int
func longCalculation(i Job) int {
duration := time.Duration(rand.Intn(1000)) * time.Millisecond
time.Sleep(duration)
fmt.Printf("Job %d complete in %v\n", i, duration)
return int(i) * 30
}
func makeJobs() []Job {
jobs := make([]Job, 0, 100)
for i := 0; i < 100; i++ {
jobs = append(jobs, Job(rand.Intn(10000)))
}
return jobs
}
func funJobOnGoRouted(incomingChannel chan Job, outGoingChannel chan int) {
for {
select {
case job := <-incomingChannel:
go func() {
result := longCalculation(job)
outGoingChannel <- result
}()
case <-time.After(300 * time.Millisecond):
return
}
}
}
func main() {
rand.Seed(time.Now().UnixNano())
jobs := makeJobs()
jobChannel := make(chan Job, 100)
resultChannel := make(chan int, 100)
go funJobOnGoRouted(jobChannel, resultChannel)
for i := 0; i < len(jobs); i++ {
job := jobs[i]
go func() { jobChannel <- job }()
}
sum := 0
loop:
for {
select {
case num := <-resultChannel:
sum += num
case <-time.After(1100 * time.Millisecond):
break loop
}
}
fmt.Println(sum)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment