/*Simple program to use WaitGroup*/packagemainimport("fmt""sync""time")// The routine spawned from main routinefuncprocess(iint,wg*sync.WaitGroup){fmt.Println("started Goroutine",i)time.Sleep(1*time.Second)fmt.Println("Goroutine",i,"done.")wg.Done()}funcmain(){no:=5varwgsync.WaitGroupfori:=0;i<no;i++{wg.Add(1)goprocess(i,&wg)}wg.Wait()fmt.Println("All the routines finished")}/*started Goroutine 4started Goroutine 2started Goroutine 3started Goroutine 0started Goroutine 1Goroutine 0 done.Goroutine 4 done.Goroutine 1 done.Goroutine 3 done.Goroutine 2 done.All the routines finished*/
type Job struct {
id int
randomno int
}
type Result struct {
job Job
sumofdigits int
}
var jobs = make(chan Job, 10)
var results = make(chan Result, 10)
func worker(wg *sync.WaitGroup) {
for job := range jobs {
output := Result{job, digits(job.randomno)}
results <- output
}
wg.Done()
}
func digits(number int) int {
sum := 0
no := number
for no != 0 {
digit := no % 10
sum += digit
no /= 10
}
time.Sleep(2 * time.Second)
return sum
}
func allocate(noOfJobs int) {
for i := 0; i < noOfJobs; i++ {
randomno := rand.Intn(999)
job := Job{i, randomno}
jobs <- job
}
close(jobs)
}
func result(done chan bool) {
for result := range results {
fmt.Printf("Job id %d, input random no %d , sum of digits %d\n", result.job.id, result.job.randomno, result.sumofdigits)
}
done <- true
}
func main() {
startTime := time.Now()
noOfJobs := 100
go allocate(noOfJobs)
done := make(chan bool)
go result(done)
noOfWorkers := 10
createWorkerPool(noOfWorkers)
<-done
endTime := time.Now()
diff := endTime.Sub(startTime)
fmt.Println("total time taken ", diff.Seconds(), "seconds")
}