Compare commits
2 Commits
34407f0dfe
...
3477d7143d
Author | SHA1 | Date |
---|---|---|
Your Name | 3477d7143d | |
Your Name | 0523a99880 |
|
@ -8,4 +8,21 @@ golang的并发通过goroutine实现,goroutine是用户态的线程,由go的
|
|||
|
||||
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线程有固定的栈内存
|
|
@ -5,21 +5,18 @@ import (
|
|||
"time"
|
||||
)
|
||||
|
||||
func hello() {
|
||||
fmt.Println("hello")
|
||||
func hello(i int) {
|
||||
fmt.Println("hello world", i)
|
||||
}
|
||||
|
||||
// 主goroutine开启,之后所有的子协程都会自行退出
|
||||
// 程序启动之后会创建一个主goroutine去执行
|
||||
func main() {
|
||||
|
||||
//通过匿名函数开启goroutine
|
||||
for i := 0; i < 10; i++ {
|
||||
go func() {
|
||||
fmt.Println(i)
|
||||
}() //事实上这个函数中的i去找到的是上面这个循环的i,所以当goroutine启动过快有可能在一个循环中找到i
|
||||
|
||||
}
|
||||
fmt.Println("this is main,2")
|
||||
time.Sleep(time.Second)
|
||||
|
||||
go func(i int) {
|
||||
fmt.Println("hello world", i)
|
||||
}(i)
|
||||
} //开启一个单独的goroutine 去执行hello函数(任务)
|
||||
fmt.Println("main")
|
||||
time.Sleep(1 * time.Second)
|
||||
//main函数结束了 由main函数启动的goroutine也都结束了
|
||||
}
|
||||
|
|
|
@ -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