go-并发

0x01 异步并发

仅作模板案列

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
package main

import (
"fmt"
"sync"
"time"
// "runtime"
)

func main() {
// runtime.GOMAXPROCS(4)
go spinner(100 * time.Millisecond)
wg := sync.WaitGroup{}

for i := 0; i < 10; i++ {
wg.Add(1)
go calc(&wg, i)
}

wg.Wait()
fmt.Println("all goroutine finish")
}

func calc(w *sync.WaitGroup, i int) {
fmt.Println("calc:", i)
time.Sleep(2 *time.Second)
defer w.Done()
}


func spinner(delay time.Duration) {
for {
for _, r := range `-\|/` {
fmt.Printf("\r%c", r)
time.Sleep(delay)
}
}
}
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
package main

import (
"fmt"
"runtime"
)

func main() {
runtime.GOMAXPROCS( runtime.NumCPU() )
c := make(chan bool, 10)
for i := 0; i < 10; i++ {
go Poc(c, i)
}

for i :=0; i < 10; i++ {
<- c
}
}

func Poc(c chan bool, index int) {
a :=1
for i := 0; i < 1000000; i++ {
a += i
}
fmt.Println( index, a )
c <- true
}

参考

https://segmentfault.com/a/1190000016703769
https://beego.me/docs/module/httplib.md
https://www.kancloud.cn/liupengjie/go/570005

坚持原创技术分享,您的支持将鼓励我继续创作!