GolangNote

Golang笔记

Golang 并发控制的两种模式

Permalink

两种常用的并发控制,使用 channel 和 WaitGroup

Go: 并发控制
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
57
58
59
60
61
62
63
64
package main

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

func main() {
	fmt.Println("Hello, 世界")
	handle1()
	handle2()
}

func handle1() {
	// 通过无缓冲通道来实现多 goroutine 并发控制

	// create channel to synchronize
	done := make(chan bool) // 无缓冲通道
	defer close(done)

	go func() {
		time.Sleep(9 * time.Second)
		fmt.Println("one done")
		done <- true
	}()

	go func() {
		time.Sleep(5 * time.Second)
		fmt.Println("two done")
		done <- true
	}()

	// wait until both are done
	for c := 0; c < 2; c++ {
		<-done
	}
	fmt.Println("handle1 done")
	// 当主 goroutine 运行到 <-done 接受 channel 的值的时候,如果该  channel 中没有数据,就会一直阻塞等待,直到有值。
}

func handle2() {
	// 通过sync包中的WaitGroup 实现并发控制

	var wg sync.WaitGroup

	wg.Add(1)
	go func(wg *sync.WaitGroup) {
		time.Sleep(5 * time.Second)
		fmt.Println("1 done")
		wg.Done()
	}(&wg)

	wg.Add(1)
	go func(wg *sync.WaitGroup) {
		time.Sleep(9 * time.Second)
		fmt.Println("2 done")
		wg.Done()
	}(&wg)
	wg.Wait()
	fmt.Println("handle2 done")

}

sync 包中,提供了 WaitGroup ,它会等待它收集的所有 goroutine 任务全部完成,在主 goroutineAdd(delta int) 索要等待 goroutine 的数量。在每一个 goroutine 完成后 Done() 表示这一个 goroutine 已经完成,当所有的 goroutine 都完成后,在主 goroutineWaitGroup 返回。

稍完善些就再添加超时功能。

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

Related articles

Golang 泛型性能初识

编程时,我们通常需要编写“泛型”函数,其中确切的数据类型并不重要。例如,您可能想编写一个简单的函数来对数字进行求和。Go 直到最近才有这个概念,但最近才添加了它(从1.18版开始)。...

Golang phantomjs 动态代理实现

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

Golang实现简单的Socks5代理

Socks5 代理较 `http/https` 代理有较好的性能,下面是借鉴某个著名开源软件的 local 实现的简单代理。...

Write a Comment to "Golang 并发控制的两种模式"

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