waitGroup
parent
0523a99880
commit
3477d7143d
|
@ -10,4 +10,19 @@ golang提供channel用来在多个goroutine之间进行通信。
|
|||
|
||||
|
||||
|
||||
只需要在调用函数前加上 go 关键字 即可开启一个goroutine
|
||||
只需要在调用函数前加上 go 关键字 即可开启一个goroutine
|
||||
|
||||
|
||||
goroutine对应的函数执行结束了,goroutine就结束了
|
||||
main函数执行完毕,由main函数创建的那些goroutine就结束了
|
||||
|
||||
如何等待所有的goroutine结束之后再执行主函数?
|
||||
sync.waitGroup对象中有三个方法
|
||||
var wg sync.waitGroup
|
||||
wg.add(1) //计数器加1
|
||||
wg.done()//计数器减1
|
||||
wg.wait()//等待所有的goroutine结束
|
||||
|
||||
|
||||
goroutine与线程
|
||||
os线程有固定的栈内存
|
|
@ -0,0 +1,40 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"math/rand"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
//waitGroup
|
||||
|
||||
func f() {
|
||||
//生成随机数
|
||||
rand.New(rand.NewSource(time.Now().UnixNano()))
|
||||
for i := 0; i < 5; i++ {
|
||||
r1 := rand.Int()
|
||||
r2 := rand.Intn(10)
|
||||
fmt.Println(r1, r2)
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
func f1(i int) {
|
||||
defer wg.Done() //任务结束后计数器-1
|
||||
time.Sleep(time.Second * time.Duration(rand.Intn(3)))
|
||||
fmt.Println(i)
|
||||
|
||||
}
|
||||
|
||||
var wg sync.WaitGroup
|
||||
|
||||
func main() {
|
||||
for i := 0; i < 10; i++ {
|
||||
wg.Add(1)
|
||||
go f1(i)
|
||||
}
|
||||
//如何知道这10个goroutine都结束了
|
||||
wg.Wait() //等待wg的计数器减为0
|
||||
|
||||
}
|
Loading…
Reference in New Issue