/*Simple program to use WaitGroup*/packagemainimport ("fmt""sync""time")// The routine spawned from main routinefuncprocess(i int, wg *sync.WaitGroup) { fmt.Println("started Goroutine", i) time.Sleep(1* time.Second) fmt.Println("Goroutine", i, "done.") wg.Done()}funcmain() { no :=5var wg sync.WaitGroupfor i :=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*/
funcworker(wg *sync.WaitGroup) { for job :=range jobs { output :=Result{job, digits(job.randomno)} results <- output } wg.Done()}funcdigits(number int) int { sum :=0 no := numberfor no !=0 { digit := no %10 sum += digit no /=10 } time.Sleep(2* time.Second)return sum}
根据任务数量分配任务,并且创建输出结果的routine
funcallocate(noOfJobs int) { for i :=0; i < noOfJobs; i++ { randomno := rand.Intn(999) job :=Job{i, randomno} jobs <- job }close(jobs)}funcresult(done chanbool) { 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}funcmain() { startTime := time.Now() noOfJobs :=100goallocate(noOfJobs) done :=make(chanbool)goresult(done) noOfWorkers :=10createWorkerPool(noOfWorkers)<-done endTime := time.Now() diff := endTime.Sub(startTime) fmt.Println("total time taken ", diff.Seconds(), "seconds")}