Home Backend Development Golang Concurrency in Go: From Basics to Advanced Concepts

Concurrency in Go: From Basics to Advanced Concepts

Oct 03, 2024 am 06:11 AM

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

1

go functionName()

Copy after login

或者使用匿名函数:

1

2

3

go func() {

    // function body

}()

Copy after login

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

package main

 

import (

    "fmt"

    "time"

)

 

func printNumbers() {

    for i := 1; i <= 5; i++ {

        time.Sleep(100 * time.Millisecond)

        fmt.Printf("%d ", i)

    }

}

 

func printLetters() {

    for i := 'a'; i <= 'e'; i++ {

        time.Sleep(150 * time.Millisecond)

        fmt.Printf("%c ", i)

    }

}

 

func main() {

    go printNumbers()

    go printLetters()

    time.Sleep(2 * time.Second)

    fmt.Println("\nMain function finished")

}

Copy after login

说明:

  • 我们定义了两个函数: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

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 <= 5; i++ {

        time.Sleep(500 * time.Millisecond) // Sleep for 500ms to simulate work

        fmt.Printf("%d ", i)

    }

}

 

// printLetters is a function that prints letters from 'a' to 'e'

// It will also be run as a goroutine

func printLetters() {

    for i := 'a'; i <= 'e'; i++ {

        time.Sleep(300 * time.Millisecond) // Sleep for 300ms to simulate work

        fmt.Printf("%c ", i)

    }

}

 

func main() {

    // Start printNumbers as a goroutine

    // The 'go' keyword before the function call creates a new goroutine

    go printNumbers()

 

    // Start printLetters as another goroutine

    go printLetters()

 

    // Sleep for 3 seconds to allow goroutines to finish

    // This is a simple way to wait, but not ideal for production code

    time.Sleep(3 * time.Second)

 

    // Print a newline for better formatting

    fmt.Println("\nMain function finished")

}

Copy after login

4.频道:

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

频道的目的

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

创建:使用 make 函数创建通道:

1

ch := make(chan int)  // Unbuffered channel of integers

Copy after login

发送:使用

1

ch <- 42  // Send the value 42 to the channel

Copy after login

Receiving: Values are received from a channel using the <- operator:

1

value := <-ch  // Receive a value from the channel

Copy after login

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

ch := make(chan int)

go func() {

    ch <- 42  // This will block until the value is received

}()

value := <-ch  // This will receive the value

Copy after login

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

ch := make(chan int, 2)

ch <- 1  // Doesn't block

ch <- 2  // Doesn't block

ch <- 3  // This will block until a value is received

Copy after login

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

func send(ch chan<- int) {

    ch <- 42

}

 

func receive(ch <-chan int) {

    value := <-ch

    fmt.Println(value)

}

Copy after login

Closing Channels

Channels can be closed to signal that no more values will be sent:

1

close(ch)

Copy after login

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

value, ok := <-ch

if !ok {

    fmt.Println("Channel is closed")

}

Copy after login

Ranging over Channels

You can use a for range loop to receive values from a channel until it's closed:

1

2

3

for value := range ch {

    fmt.Println(value)

}

Copy after login

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 of this Website
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

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

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1658
14
PHP Tutorial
1257
29
C# Tutorial
1231
24
Golang's Purpose: Building Efficient and Scalable Systems Golang's Purpose: Building Efficient and Scalable Systems Apr 09, 2025 pm 05:17 PM

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 and C  : Concurrency vs. Raw Speed Golang and C : Concurrency vs. Raw Speed Apr 21, 2025 am 12:16 AM

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 vs. Python: Key Differences and Similarities Golang vs. Python: Key Differences and Similarities Apr 17, 2025 am 12:15 AM

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 vs. Python: Performance and Scalability Golang vs. Python: Performance and Scalability Apr 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's Impact: Speed, Efficiency, and Simplicity Golang's Impact: Speed, Efficiency, and Simplicity Apr 14, 2025 am 12:11 AM

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

C   and Golang: When Performance is Crucial C and Golang: When Performance is Crucial Apr 13, 2025 am 12:11 AM

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.

The Performance Race: Golang vs. C The Performance Race: Golang vs. C Apr 16, 2025 am 12:07 AM

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.

Golang and C  : The Trade-offs in Performance Golang and C : The Trade-offs in Performance Apr 17, 2025 am 12:18 AM

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.

See all articles