Golang 协程例子

package main

import (
	"fmt"
	"sync"
	"time"
)

var waitgroup sync.WaitGroup

func RunFunc1(num int) {
	fmt.Println("Now Run:", num)
	time.Sleep(time.Duration(num) * time.Second)
	waitgroup.Done() //任务完成,将任务队列中的任务数量-1,其实.Done就是.Add(-1)
}

func main() {
	s := time.Now()
	for i := 0; i < 6; i++ {
		waitgroup.Add(1) //每创建一个goroutine,就把任务队列中任务的数量+1
		go RunFunc1(i)
	}
	waitgroup.Wait() //.Wait()这里会发生阻塞,直到队列中所有的任务结束就会解除阻塞

	fmt.Println("所有 goroutine 都已运行完成!花费时间:", time.Since(s)-time.Duration(5)*time.Second)
}

运行结果

[ `go run waitgroup.go` | done: 5.194994395s ]
	Now Run: 2
	Now Run: 4
	Now Run: 3
	Now Run: 1
	Now Run: 0
	Now Run: 5
	所有 goroutine 都已运行完成!花费时间: 5.001283502s