一个 GoLang 协程并发的典型例子
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
package main
import (
"fmt"
"runtime"
"time"
)
func get_sum_of_divisible(num int, divider int, resultChan chan int) {
sum := 0
for value := 0; value < num; value++ {
if value%divider == 0 {
sum += value
}
}
resultChan <- sum
}
func main() {
runtime.GOMAXPROCS(runtime.NumCPU())
LIMIT := 1000
//用于被15除结果
job1 := make(chan int, 1)
//用于被3,5除结果
job2 := make(chan int, 2)
t_start := time.Now()
go get_sum_of_divisible(LIMIT, 15, job1)
go get_sum_of_divisible(LIMIT, 3, job2)
go get_sum_of_divisible(LIMIT, 5, job2)
sum15 := <-job1
sum3, sum5 := <-job2, <-job2
sum := sum3 + sum5 - sum15
t_end := time.Now()
fmt.Println(sum)
fmt.Println(t_end.Sub(t_start))
}
运行输出:
1
2
233168
51.89µs
本文网址: https://golangnote.com/topic/70.html 转摘请注明来源