GolangNote

Golang笔记

尽量用标准库来实现并发,可以避免管理上开销

Permalink

尽量用标准库来实现并发,这样可以避免管理上开销,下面是一个示例

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

import (
  "fmt"
  "sync"
  "time"
)

type someDataStruct struct {
  Val int
}

var wg sync.WaitGroup

func main() {

  t1 := time.Now()

  tasks := make(chan someDataStruct, 40)

  for i := 0; i < 40; i++ {
    wg.Add(1)

    go func() {
      for data := range tasks {
        // do some work on data
        fmt.Println(data.Val + 1)
      }
      wg.Done()
    }()

    someData := someDataStruct{i}
    // Push to it like this:
    tasks <- someData
  }

  // Finish like this
  close(tasks)
  wg.Wait()

  t2 := time.Now()
  fmt.Println("消耗时间:", t2.Sub(t1), "秒")
}

运行输出:

Bash: out put
1
2
3
4
5
6
7
8
1
2
3
...
38
39
40
消耗时间: 3.848086ms 秒

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

Related articles

Write a Comment to "尽量用标准库来实现并发,可以避免管理上开销"

Submit Comment Login
Based on Golang + fastHTTP + sdb | go1.17.1 Processed in 0ms