search
HomeBackend DevelopmentGolangConcurrency in Go: From Basics to Advanced Concepts

Concurrency in Go: From Basics to Advanced Concepts

目录

  1. 并发简介
  2. 并发与并行
  3. Go 例程:并发的构建块
  4. 通道:Go 例程之间的通信
  5. Select 语句:管理多个通道
  6. 同步原语
  7. 并发模式
  8. 上下文包:管理取消和 超时。
  9. 最佳实践和常见陷阱**

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 关键字,后跟函数调用:

go functionName()

或者使用匿名函数:

go func() {
    // function body
}()

Go-routine 调度:

  • Go 运行时使用 M:N 调度程序,其中 M 个 go 例程被调度到 N 个操作系统线程上。
  • 这个调度程序是非抢占式的,这意味着 Go 例程在空闲或逻辑阻塞时会产生控制权。

通讯与同步:

  • Goroutine 通常使用通道进行通信,遵循“不要通过共享内存进行通信;通过通信来共享内存”的原则。
  • 对于简单的同步,您可以使用像sync.WaitGroup或sync.Mutex这样的原语。

示例及说明:

package main

import (
    "fmt"
    "time"
)

func printNumbers() {
    for i := 1; i 



<p><strong>说明:</strong></p>

  • 我们定义了两个函数:printNumbers 和 printLetters。
  • 在 main 中,我们使用 go 关键字将这些函数作为 goroutine 启动。
  • 然后 main 函数休眠 2 秒,让 goroutine 完成。
  • 如果没有 goroutine,这些函数将按顺序运行。对于 goroutine,它们是同时运行的。
  • 输出将显示数字和字母交错,演示并发执行。

Goroutine 生命周期:

  • goroutine 在使用 go 关键字创建时启动。
  • 当其功能完成或程序退出时,它终止。
  • 如果管理不当,Goroutines 可能会泄漏,因此确保它们可以退出非常重要。

最佳实践:

  • 不要在库中创建 goroutine;让调用者控制并发。
  • 创建无限数量的 goroutine 时要小心。
  • 使用通道或同步原语在 goroutine 之间进行协调。
  • 考虑使用工作池来有效管理多个 goroutine。

带有 go 例程解释的简单示例

package main

import (
    "fmt"
    "time"
)

// printNumbers is a function that prints numbers from 1 to 5
// It will be run as a goroutine
func printNumbers() {
    for i := 1; i 



<p><strong>4.频道:</strong></p>

<p>通道是 Go 中的一项核心功能,它允许 go 例程相互通信并同步执行。它们为一个 go 例程提供了一种将数据发送到另一个 go 例程的方法。</p>

<p><strong>频道的目的</strong></p>

<p>Go 中的通道有两个主要用途:<br>
a) 通信:它们允许 goroutine 相互发送和接收值。<br>
b) 同步:它们可用于跨 Goroutine 同步执行。</p>

<p>创建:使用 make 函数创建通道:<br>
</p>

<pre class="brush:php;toolbar:false">ch := make(chan int)  // Unbuffered channel of integers

发送:使用

ch 



<p>Receiving: Values are received from a channel using the 
</p>

<pre class="brush:php;toolbar:false">value := 



<p><strong>Types of Channels</strong></p>

<p>a) Unbuffered Channels:</p>

  • Created without a capacity: ch := make(chan int)
  • Sending blocks until another goroutine receives.
  • Receiving blocks until another goroutine sends.
ch := make(chan int)
go func() {
    ch 



<p>b) Buffered Channels:</p>

  • 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.
ch := make(chan int, 2)
ch 



<p><strong>Channel Directions</strong></p>

<p>Channels can be directional or bidirectional:</p>

  • Bidirectional: chan T
  • Send-only: chan
  • Receive-only:

Example :

func send(ch chan



<p><strong>Closing Channels</strong></p>

<p>Channels can be closed to signal that no more values will be sent:<br>
</p>

<pre class="brush:php;toolbar:false">close(ch)

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:

value, ok := 



<p><strong>Ranging over Channels</strong></p>

<p>You can use a for range loop to receive values from a channel until it's closed:<br>
</p>

<pre class="brush:php;toolbar:false">for value := range ch {
    fmt.Println(value)
}

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!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Choosing Between Golang and Python: The Right Fit for Your ProjectChoosing Between Golang and Python: The Right Fit for Your ProjectApr 19, 2025 am 12:21 AM

Golangisidealforperformance-criticalapplicationsandconcurrentprogramming,whilePythonexcelsindatascience,rapidprototyping,andversatility.1)Forhigh-performanceneeds,chooseGolangduetoitsefficiencyandconcurrencyfeatures.2)Fordata-drivenprojects,Pythonisp

Golang: Concurrency and Performance in ActionGolang: Concurrency and Performance in ActionApr 19, 2025 am 12:20 AM

Golang achieves efficient concurrency through goroutine and channel: 1.goroutine is a lightweight thread, started with the go keyword; 2.channel is used for secure communication between goroutines to avoid race conditions; 3. The usage example shows basic and advanced usage; 4. Common errors include deadlocks and data competition, which can be detected by gorun-race; 5. Performance optimization suggests reducing the use of channel, reasonably setting the number of goroutines, and using sync.Pool to manage memory.

Golang vs. Python: Which Language Should You Learn?Golang vs. Python: Which Language Should You Learn?Apr 19, 2025 am 12:20 AM

Golang is more suitable for system programming and high concurrency applications, while Python is more suitable for data science and rapid development. 1) Golang is developed by Google, statically typing, emphasizing simplicity and efficiency, and is suitable for high concurrency scenarios. 2) Python is created by Guidovan Rossum, dynamically typed, concise syntax, wide application, suitable for beginners and data processing.

Golang vs. Python: Performance and ScalabilityGolang vs. Python: Performance and ScalabilityApr 19, 2025 am 12:18 AM

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.

Golang vs. Other Languages: A ComparisonGolang vs. Other Languages: A ComparisonApr 19, 2025 am 12:11 AM

Go language has unique advantages in concurrent programming, performance, learning curve, etc.: 1. Concurrent programming is realized through goroutine and channel, which is lightweight and efficient. 2. The compilation speed is fast and the operation performance is close to that of C language. 3. The grammar is concise, the learning curve is smooth, and the ecosystem is rich.

Golang and Python: Understanding the DifferencesGolang and Python: Understanding the DifferencesApr 18, 2025 am 12:21 AM

The main differences between Golang and Python are concurrency models, type systems, performance and execution speed. 1. Golang uses the CSP model, which is suitable for high concurrent tasks; Python relies on multi-threading and GIL, which is suitable for I/O-intensive tasks. 2. Golang is a static type, and Python is a dynamic type. 3. Golang compiled language execution speed is fast, and Python interpreted language development is fast.

Golang vs. C  : Assessing the Speed DifferenceGolang vs. C : Assessing the Speed DifferenceApr 18, 2025 am 12:20 AM

Golang is usually slower than C, but Golang has more advantages in concurrent programming and development efficiency: 1) Golang's garbage collection and concurrency model makes it perform well in high concurrency scenarios; 2) C obtains higher performance through manual memory management and hardware optimization, but has higher development complexity.

Golang: A Key Language for Cloud Computing and DevOpsGolang: A Key Language for Cloud Computing and DevOpsApr 18, 2025 am 12:18 AM

Golang is widely used in cloud computing and DevOps, and its advantages lie in simplicity, efficiency and concurrent programming capabilities. 1) In cloud computing, Golang efficiently handles concurrent requests through goroutine and channel mechanisms. 2) In DevOps, Golang's fast compilation and cross-platform features make it the first choice for automation tools.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use