GolangNote

Golang笔记

一个GoLang 协程并发的典型例子

Permalink

一个 GoLang 协程并发的典型例子

Go: 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))
}

运行输出:

Bash: GoLang 协程并发计算结果
1
2
233168
51.89µs

本文网址: https://golangnote.com/topic/70.html 转摘请注明来源

Related articles

Golang phantomjs 动态代理实现

phantomjs 是个很优秀的软件,虽然现在被chrome headless 抢了风头,但在某些特定场合,使用phantomjs 还是很方便,这里是介绍使用Go 实现动态代理。...

Write a Comment to "一个GoLang 协程并发的典型例子"

Submit Comment Login
Based on Golang + fastHTTP + sdb | go1.22.3 Processed in 5ms