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

Concurrency in Go: From Basics to Advanced Concepts

Linda Hamilton
Release: 2024-10-03 06:11:30
Original
458 people have browsed it

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()
Copy after login

或者使用匿名函数:

go func() {
    // function body
}()
Copy after login

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 <= 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 例程解释的简单示例

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 函数创建通道:

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

发送:使用

ch <- 42  // Send the value 42 to the channel
Copy after login

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

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.
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.
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 :

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:

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:

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:

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!

source:dev.to
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template