Concurrency in Go: From Basics to Advanced Concepts
目录
- 并发简介
- 并发与并行
- Go 例程:并发的构建块
- 通道:Go 例程之间的通信
- Select 语句:管理多个通道
- 同步原语
- 并发模式
- 上下文包:管理取消和 超时。
- 最佳实践和常见陷阱**
1.并发简介
并发是同时处理多个任务的能力。在 Go 中,并发性是一等公民,内置于该语言的核心设计中。 Go 的并发方法基于通信顺序进程(CSP),该模型强调进程之间的通信而不是共享内存。
2.并发与并行:
Go 例程支持并发,这是独立执行进程的组合。
如果系统有多个 CPU 核心并且 Go 运行时安排 go 例程并行运行,则可能会发生并行(同时执行)。
3。 Go 例程:
并发的构建块是 Go 例程,是由 Go 运行时管理的轻量级线程。它是与其他函数或方法同时运行的函数或方法。 Go 例程是 Go 并发模型的基础。
主要特征:
- 轻量级:Go 例程比操作系统线程轻得多。您可以轻松创建数千个 go 例程,而不会显着影响性能。
- 由 Go 运行时管理:Go 调度程序处理可用操作系统线程之间的 go 例程分配。
- 廉价创建:启动 go 例程就像在函数调用之前使用 go 关键字一样简单。
- 堆栈大小:Go 例程从一个小堆栈(大约 2KB)开始,可以根据需要增长和缩小。
创建 Go 例程:
要启动 go 例程,只需使用 go 关键字,后跟函数调用:
1 |
|
或者使用匿名函数:
1 2 3 |
|
Go-routine 调度:
- Go 运行时使用 M:N 调度程序,其中 M 个 go 例程被调度到 N 个操作系统线程上。
- 这个调度程序是非抢占式的,这意味着 Go 例程在空闲或逻辑阻塞时会产生控制权。
通讯与同步:
- Goroutine 通常使用通道进行通信,遵循“不要通过共享内存进行通信;通过通信来共享内存”的原则。
- 对于简单的同步,您可以使用像sync.WaitGroup或sync.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 |
|
说明:
- 我们定义了两个函数:printNumbers 和 printLetters。
- 在 main 中,我们使用 go 关键字将这些函数作为 goroutine 启动。
- 然后 main 函数休眠 2 秒,让 goroutine 完成。
- 如果没有 goroutine,这些函数将按顺序运行。对于 goroutine,它们是同时运行的。
- 输出将显示数字和字母交错,演示并发执行。
Goroutine 生命周期:
- goroutine 在使用 go 关键字创建时启动。
- 当其功能完成或程序退出时,它终止。
- 如果管理不当,Goroutines 可能会泄漏,因此确保它们可以退出非常重要。
最佳实践:
- 不要在库中创建 goroutine;让调用者控制并发。
- 创建无限数量的 goroutine 时要小心。
- 使用通道或同步原语在 goroutine 之间进行协调。
- 考虑使用工作池来有效管理多个 goroutine。
带有 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 |
|
4.频道:
通道是 Go 中的一项核心功能,它允许 go 例程相互通信并同步执行。它们为一个 go 例程提供了一种将数据发送到另一个 go 例程的方法。
频道的目的
Go 中的通道有两个主要用途:
a) 通信:它们允许 goroutine 相互发送和接收值。
b) 同步:它们可用于跨 Goroutine 同步执行。
创建:使用 make 函数创建通道:
1 |
|
发送:使用
1 |
|
Receiving: Values are received from a channel using the <- operator:
1 |
|
Types of Channels
a) Unbuffered Channels:
- Created without a capacity: ch := make(chan int)
- Sending blocks until another goroutine receives.
- Receiving blocks until another goroutine sends.
1 2 3 4 5 |
|
b) Buffered Channels:
- Created with a capacity: ch := make(chan int, 3)
- Sending only blocks when the buffer is full.
- Receiving only blocks when the buffer is empty.
1 2 3 4 |
|
Channel Directions
Channels can be directional or bidirectional:
- Bidirectional: chan T
- Send-only: chan<- T
- Receive-only: <-chan T
Example :
1 2 3 4 5 6 7 8 |
|
Closing Channels
Channels can be closed to signal that no more values will be sent:
1 |
|
Receiving from a closed channel:
If the channel is empty, it returns the zero value of the channel's type.
You can check if a channel is closed using a two-value receive:
1 2 3 4 |
|
Ranging over Channels
You can use a for range loop to receive values from a channel until it's closed:
1 2 3 |
|
Hey, Thank you for staying until the end! I appreciate you being valuable reader and learner. Please follow me here and also on my Linkedin and GitHub .
The above is the detailed content of Concurrency in Go: From Basics to Advanced Concepts. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











Go language performs well in building efficient and scalable systems. Its advantages include: 1. High performance: compiled into machine code, fast running speed; 2. Concurrent programming: simplify multitasking through goroutines and channels; 3. Simplicity: concise syntax, reducing learning and maintenance costs; 4. Cross-platform: supports cross-platform compilation, easy deployment.

Golang is better than C in concurrency, while C is better than Golang in raw speed. 1) Golang achieves efficient concurrency through goroutine and channel, which is suitable for handling a large number of concurrent tasks. 2)C Through compiler optimization and standard library, it provides high performance close to hardware, suitable for applications that require extreme optimization.

Golang and Python each have their own advantages: Golang is suitable for high performance and concurrent programming, while Python is suitable for data science and web development. Golang is known for its concurrency model and efficient performance, while Python is known for its concise syntax and rich library ecosystem.

Golang is better than Python in terms of performance and scalability. 1) Golang's compilation-type characteristics and efficient concurrency model make it perform well in high concurrency scenarios. 2) Python, as an interpreted language, executes slowly, but can optimize performance through tools such as Cython.

Goimpactsdevelopmentpositivelythroughspeed,efficiency,andsimplicity.1)Speed:Gocompilesquicklyandrunsefficiently,idealforlargeprojects.2)Efficiency:Itscomprehensivestandardlibraryreducesexternaldependencies,enhancingdevelopmentefficiency.3)Simplicity:

C is more suitable for scenarios where direct control of hardware resources and high performance optimization is required, while Golang is more suitable for scenarios where rapid development and high concurrency processing are required. 1.C's advantage lies in its close to hardware characteristics and high optimization capabilities, which are suitable for high-performance needs such as game development. 2.Golang's advantage lies in its concise syntax and natural concurrency support, which is suitable for high concurrency service development.

Golang and C each have their own advantages in performance competitions: 1) Golang is suitable for high concurrency and rapid development, and 2) C provides higher performance and fine-grained control. The selection should be based on project requirements and team technology stack.

The performance differences between Golang and C are mainly reflected in memory management, compilation optimization and runtime efficiency. 1) Golang's garbage collection mechanism is convenient but may affect performance, 2) C's manual memory management and compiler optimization are more efficient in recursive computing.
