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 实现 10 进制转 N 进制

给定一个不没有重复字符的字符串,如 `[0-9,a-z]`,把一个 10 进制数字转为,该字符集的字符串。应用场合如汽车牌、顺序计数。...

Golang 把cookie 字符串解析为cookie 结构

在做爬虫时有时候会遇到需要带已登录的 cookie 请求,这个时候最简单的方法是在浏览器登录后,在开发者面板找到cookie 字符串,然后拷贝粘贴。这就面临一个问题需要把cookie 字符串解析成Go 语言 cookie 结构体。...

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

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