一个使用 Goroutines 和 Gosched 的例子
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
package main
import (
"fmt"
"math"
"sync"
"time"
)
func sum(id int) {
var x int64
for i := int64(0); i < math.MaxUint32; i++ {
x += i
}
println(id, x)
}
func main() {
t1 := time.Now()
wg := new(sync.WaitGroup)
wg.Add(2)
for i := 0; i < 2; i++ {
go func(id int) {
defer wg.Done()
sum(id)
}(i)
}
wg.Wait()
t2 := time.Now()
fmt.Println("消耗时间:", t2.Sub(t1), "秒")
}
运行输出:
1
2
3
0 9223372030412324865
1 9223372030412324865
消耗时间: 10.334185001s 秒
使用 Gosched 机制: Gosched很像yield,会暂停目前goroutine,把Thread让给别人。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
package main
import (
"fmt"
"runtime"
"sync"
"time"
)
type HandleFunc func(int)
func Handler(id int, handleFnc HandleFunc, wg *sync.WaitGroup) {
defer wg.Done()
handleFnc(id)
}
func HasGoSched(id int) {
for i := 0; i < 10; i++ {
fmt.Println(id, i)
if i == 3 || i == 8 {
runtime.Gosched()
}
}
}
func SayHello(id int) {
fmt.Println(id, "Hello World!")
}
func OtherProc(id int) {
for i := 0; i < 10; i++ {
fmt.Println(id, i)
if i == 5 {
runtime.Gosched()
}
}
}
func main() {
t1 := time.Now()
wg := new(sync.WaitGroup)
wg.Add(3)
go Handler(0, HasGoSched, wg)
go Handler(1, SayHello, wg)
go Handler(2, OtherProc, wg)
wg.Wait()
t2 := time.Now()
fmt.Println("消耗时间:", t2.Sub(t1), "秒")
}
运行输出:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
0 0
0 1
0 2
0 3
1 Hello World!
2 0
2 1
2 2
2 3
2 4
2 5
0 4
0 5
0 6
0 7
0 8
2 6
2 7
2 8
2 9
0 9
消耗时间: 1.866552ms 秒
本文网址: https://golangnote.com/topic/68.html 转摘请注明来源