GolangNote

Golang笔记

Golang 管道并发计算示例

Permalink

下面介绍用两种方式做管道并发计算:sync.Mutex 和 chan

Golang 管道并发计算

用 chan

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

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

// 打印100次
var num int = 100

// 用两个chan进行通知
func Print(content string, ch chan int, ch2 chan int, wg *sync.WaitGroup) {
  if "A" == content {
    // 第一个,所以要接收最后一个chan,但是不打印
    for i := 0; i <= num; i++ {
      <-ch2

      if i < num {
        fmt.Println(content)
        ch <- i
      }
    }
  } else {
    for i := 0; i < num; i++ {
      <-ch2
      fmt.Println(content)
      ch <- i
    }
  }
  wg.Done()
}

func main() {
  var wg sync.WaitGroup
  wg.Add(3)

  ch1 := make(chan int)
  ch2 := make(chan int)
  ch3 := make(chan int)

  start := time.Now()

  go Print("A", ch1, ch3, &wg)
  go Print("B", ch2, ch1, &wg)
  go Print("C", ch3, ch2, &wg)

  // 先触发
  ch3 <- 1

  wg.Wait()

  // 计时
  duration := time.Since(start)
  fmt.Println(duration.Seconds())
}

sync.Mutex

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

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

var m *sync.Mutex = new(sync.Mutex)

var i = 0
var max = 300

func Print(content string, divNum int, wg *sync.WaitGroup) {
  for i <= max {
    m.Lock()
    if i%3 == divNum {
      fmt.Println(content)
      i++
    }
    m.Unlock()
    runtime.Gosched()  // 主动让出CPU
  }
  wg.Done()
}

func main() {
  var wg sync.WaitGroup
  wg.Add(3)

  start := time.Now()

  go Print("A", 0, &wg)
  go Print("B", 1, &wg)
  go Print("C", 2, &wg)

  wg.Wait()

  duration := time.Since(start)
  fmt.Println(duration.Seconds())
}

Go 使用 sync.Mutex 性能低的解决方案:

m.Unlock() 后面添加 runtime.Gosched() ,主动让出 CPU

Related articles

golang snappy 示例

snappy 是 google 开源的一种高效的压缩算法,这里是 golang 实现的 snappy 压缩示例...

Write a Comment to "Golang 管道并发计算示例"

Submit Comment Login
Based on Golang + fastHTTP + youdb | go1.16 Processed in 1ms