首頁 後端開發 Golang 透過直覺的視覺效果了解 Golang 中的 Goroutines 和 Channel

透過直覺的視覺效果了解 Golang 中的 Goroutines 和 Channel

Dec 30, 2024 pm 04:18 PM

⚠️ 這個系列如何進行?

1。運行每個範例:不要只閱讀程式碼。輸入它,運行它,然後觀察其行為。
2。實驗和打破常規: 刪除睡眠並看看會發生什麼,更改通道緩衝區大小,修改 goroutine 計數。
打破東西會教你它們是如何運作的
3。關於行為的原因: 在執行修改後的程式碼之前,嘗試預測結果。當您看到意外行為時,請停下來思考原因。挑戰解釋。
4。建立心理模型:每個視覺化代表一個概念。嘗試為修改後的程式碼繪製自己的圖表。

Understanding Goroutines and Channels in Golang with Intuitive Visuals

這是「掌握 Go 並發」系列的 第 1 部分,我們將介紹:

  • goroutine 的工作原理及其生命週期
  • goroutines 之間的通道通訊
  • 緩衝通道及其用例
  • 實際範例與視覺化

我們將從基礎知識開始,逐步發展如何有效使用它們的直覺。

這會有點長,相當長,所以做好準備。

Understanding Goroutines and Channels in Golang with Intuitive Visuals

我們將親力親為完成整個過程。

Goroutine 的基礎

讓我們從一個下載多個檔案的簡單程式開始。

package main

import (
    "fmt"
    "time"
)

func downloadFile(filename string) {
    fmt.Printf("Starting download: %s\n", filename)
    // Simulate file download with sleep
    time.Sleep(2 * time.Second)
    fmt.Printf("Finished download: %s\n", filename)
}

func main() {
    fmt.Println("Starting downloads...")

    startTime := time.Now()

    downloadFile("file1.txt")
    downloadFile("file2.txt")
    downloadFile("file3.txt")

    elapsedTime := time.Since(startTime)

    fmt.Printf("All downloads completed! Time elapsed: %s\n", elapsedTime)
}
登入後複製
登入後複製
登入後複製
登入後複製
登入後複製

Understanding Goroutines and Channels in Golang with Intuitive Visuals

程式總共需要 6 秒,因為每個 2 秒的下載必須在下一個開始之前完成。讓我們想像一下:

Understanding Goroutines and Channels in Golang with Intuitive Visuals

我們可以縮短這個時間,讓我們修改我們的程式以使用go例程

注意:函數呼叫前使用 go 關鍵字

package main

import (
    "fmt"
    "time"
)

func downloadFile(filename string) {
    fmt.Printf("Starting download: %s\n", filename)
    // Simulate file download with sleep
    time.Sleep(2 * time.Second)
    fmt.Printf("Finished download: %s\n", filename)
}

func main() {
    fmt.Println("Starting downloads...")

    // Launch downloads concurrently
    go downloadFile("file1.txt")
    go downloadFile("file2.txt")
    go downloadFile("file3.txt")

    fmt.Println("All downloads completed!")
}
登入後複製
登入後複製
登入後複製

等等什麼?沒有列印任何內容?為什麼?

Understanding Goroutines and Channels in Golang with Intuitive Visuals

讓我們想像一下這一點,以了解可能發生的情況。

Understanding Goroutines and Channels in Golang with Intuitive Visuals

從上面的視覺化中,我們了解到 main 函數在 goroutine 完成之前就存在了。一項觀察結果是,所有 goroutine 的生命週期都依賴 main 函數。

注意:main函數本身就是一個goroutine;)

為了解決這個問題,我們需要一種方法讓主 goroutine 等待其他 goroutine 完成。有幾種方法可以做到這一點:

  1. 等待幾秒鐘(駭客方式)
  2. 使用 WaitGroup(正確的方法,下一步)
  3. 使用頻道(我們將在下面介紹)

讓我們等待幾秒鐘讓 go 程式完成。

package main

import (
    "fmt"
    "time"
)

func downloadFile(filename string) {
    fmt.Printf("Starting download: %s\n", filename)
    // Simulate file download with sleep
    time.Sleep(2 * time.Second)
    fmt.Printf("Finished download: %s\n", filename)
}

func main() {
    fmt.Println("Starting downloads...")

    startTime := time.Now()

    downloadFile("file1.txt")
    downloadFile("file2.txt")
    downloadFile("file3.txt")

    elapsedTime := time.Since(startTime)

    fmt.Printf("All downloads completed! Time elapsed: %s\n", elapsedTime)
}
登入後複製
登入後複製
登入後複製
登入後複製
登入後複製

問題是,我們可能不知道 goroutine 可能需要多長時間。在這種情況下,我們每個人都有固定的時間,但在實際場景中,我們知道下載時間會有所不同。

來了sync.WaitGroup

Go中的sync.WaitGroup是一種並發控制機制,用於等待一組goroutines執行完成。

在這裡讓我們看看它的實際效果並視覺化:

package main

import (
    "fmt"
    "time"
)

func downloadFile(filename string) {
    fmt.Printf("Starting download: %s\n", filename)
    // Simulate file download with sleep
    time.Sleep(2 * time.Second)
    fmt.Printf("Finished download: %s\n", filename)
}

func main() {
    fmt.Println("Starting downloads...")

    // Launch downloads concurrently
    go downloadFile("file1.txt")
    go downloadFile("file2.txt")
    go downloadFile("file3.txt")

    fmt.Println("All downloads completed!")
}
登入後複製
登入後複製
登入後複製

Understanding Goroutines and Channels in Golang with Intuitive Visuals

讓我們可視化這一點並了解sync.WaitGroup 的工作原理:

Understanding Goroutines and Channels in Golang with Intuitive Visuals

計數器機制:

  • WaitGroup 維護一個內部計數器
  • wg.Add(n) 將計數器增加 n
  • wg.Done() 將計數器減 1
  • wg.Wait() 阻塞,直到計數器達到 0

同步流程:

  • 主 Goroutine 在啟動 Goroutines 之前呼叫 Add(3)
  • 每個 goroutine 完成時都會呼叫 Done()
  • 主協程在 Wait() 處被阻塞,直到計數器達到 0
  • 當計數器達到 0 時,程式繼續並乾淨地退出

要避免的常見陷阱
package main

import (
    "fmt"
    "time"
)

func downloadFile(filename string) {
    fmt.Printf("Starting download: %s\n", filename)
    // Simulate file download with sleep
    time.Sleep(2 * time.Second)
    fmt.Printf("Finished download: %s\n", filename)
}

func main() {
    fmt.Println("Starting downloads...")

    startTime := time.Now() // Record start time

    go downloadFile("file1.txt")
    go downloadFile("file2.txt")
    go downloadFile("file3.txt")

    // Wait for goroutines to finish
    time.Sleep(3 * time.Second)

    elapsedTime := time.Since(startTime)

    fmt.Printf("All downloads completed! Time elapsed: %s\n", elapsedTime)
}
登入後複製
登入後複製

頻道

這樣我們就很好地理解了 goroutine 是如何運作的。不,兩個 Go 例程如何通訊?這就是頻道發揮作用的地方。

Go 中的

Channels 是一個強大的並發原語,用於 goroutine 之間的通信。它們為 goroutine 提供了一種安全共享資料的方法。

將通道視為管道:一個 goroutine 可以將資料傳送到通道,另一個 goroutine 可以接收資料。

以下是一些屬性:

  1. 通道本質上是阻塞的。
  2. A 送到通道操作 ch 阻塞直到其他 Goroutine 從通道接收。
  3. 從通道接收操作阻塞直到其他goroutine送到通道。
package main

import (
    "fmt"
    "time"
)

func downloadFile(filename string) {
    fmt.Printf("Starting download: %s\n", filename)
    // Simulate file download with sleep
    time.Sleep(2 * time.Second)
    fmt.Printf("Finished download: %s\n", filename)
}

func main() {
    fmt.Println("Starting downloads...")

    startTime := time.Now()

    downloadFile("file1.txt")
    downloadFile("file2.txt")
    downloadFile("file3.txt")

    elapsedTime := time.Since(startTime)

    fmt.Printf("All downloads completed! Time elapsed: %s\n", elapsedTime)
}
登入後複製
登入後複製
登入後複製
登入後複製
登入後複製

Understanding Goroutines and Channels in Golang with Intuitive Visuals

為什麼 ch

Understanding Goroutines and Channels in Golang with Intuitive Visuals

讓我們透過加入 goroutine 來解決這個問題

package main

import (
    "fmt"
    "time"
)

func downloadFile(filename string) {
    fmt.Printf("Starting download: %s\n", filename)
    // Simulate file download with sleep
    time.Sleep(2 * time.Second)
    fmt.Printf("Finished download: %s\n", filename)
}

func main() {
    fmt.Println("Starting downloads...")

    // Launch downloads concurrently
    go downloadFile("file1.txt")
    go downloadFile("file2.txt")
    go downloadFile("file3.txt")

    fmt.Println("All downloads completed!")
}
登入後複製
登入後複製
登入後複製

讓我們想像一下:

Understanding Goroutines and Channels in Golang with Intuitive Visuals

這次訊息從不同的Goroutine 發送,因此主Goroutine 在發送到通道時不會被阻塞,因此它會移動到msg :=

使用通道修復 main 不等其他問題

現在讓我們使用channel來修復文件下載器問題(main不等待其他人完成)。

package main

import (
    "fmt"
    "time"
)

func downloadFile(filename string) {
    fmt.Printf("Starting download: %s\n", filename)
    // Simulate file download with sleep
    time.Sleep(2 * time.Second)
    fmt.Printf("Finished download: %s\n", filename)
}

func main() {
    fmt.Println("Starting downloads...")

    startTime := time.Now() // Record start time

    go downloadFile("file1.txt")
    go downloadFile("file2.txt")
    go downloadFile("file3.txt")

    // Wait for goroutines to finish
    time.Sleep(3 * time.Second)

    elapsedTime := time.Since(startTime)

    fmt.Printf("All downloads completed! Time elapsed: %s\n", elapsedTime)
}
登入後複製
登入後複製

Understanding Goroutines and Channels in Golang with Intuitive Visuals

可視化它:

Understanding Goroutines and Channels in Golang with Intuitive Visuals

讓我們進行一次演練以更好地理解:

節目開始

主協程建立完成通道
啟動三個下載 goroutine
每個 goroutine 都會獲得對同一通道的引用

下載執行:

  1. 所有三個下載同時運行
  2. 每個需要2秒
  3. 他們可能會以任何順序完成

頻道循環:

  1. 主協程進入迴圈: for i := 0;我
  2. 每個
  3. 循環確保我們等待所有三個完成訊號

Understanding Goroutines and Channels in Golang with Intuitive Visuals

循環行為:

  1. 迭代 1:阻塞至首次下載完成
  2. 迭代 2:阻塞直到第二次下載完成
  3. 迭代 3:阻塞至最終下載完成

完成順序並不重要!

觀察
⭐ 每次發送(完成 ⭐ 主協程透過循環協調一切

兩個goroutine如何通信?

我們已經了解了兩個 goroutine 如何進行溝通。什麼時候?一直以來。 我們不要忘記 main 函數也是一個 goroutine

package main

import (
    "fmt"
    "time"
)

func downloadFile(filename string) {
    fmt.Printf("Starting download: %s\n", filename)
    // Simulate file download with sleep
    time.Sleep(2 * time.Second)
    fmt.Printf("Finished download: %s\n", filename)
}

func main() {
    fmt.Println("Starting downloads...")

    startTime := time.Now()

    downloadFile("file1.txt")
    downloadFile("file2.txt")
    downloadFile("file3.txt")

    elapsedTime := time.Since(startTime)

    fmt.Printf("All downloads completed! Time elapsed: %s\n", elapsedTime)
}
登入後複製
登入後複製
登入後複製
登入後複製
登入後複製

讓我們想像一下並試運行一下:

Understanding Goroutines and Channels in Golang with Intuitive Visuals

試運轉:

程式開始(t=0ms)

  • 主協程初始化三個通道:
    • ch:用於訊息。
    • senderDone:表示發送者完成。
    • receiveDone:表示接收器完成。
  • 主協程啟動兩個協程:
    • 寄件者。
    • 接收器。
  • 主 Goroutine 區塊,等待來自

第一則訊息(t=1ms)

  1. 發送者將「訊息1」傳送到ch通道。
  2. 接收者醒來並處理訊息:
    • 列印:「已收到:訊息 1」
  3. 傳送者休眠 100 毫秒。

第二則訊息(t=101ms)

  1. 發送者醒來並向ch通道發送「訊息2」。
  2. 接收方處理訊息:
    • 列印:「已收到:訊息 2」
  3. 傳送者再休眠 100 毫秒。

第三則訊息(t=201ms)

  1. 發送者醒來並向ch通道發送「訊息3」。
  2. 接收方處理訊息:
    • 列印:「已收到:訊息 3」
  3. 發送者最後一次睡覺。

通道關閉(t=301ms)

  1. 發送者完成睡眠並關閉 ch 通道。
  2. 發送者向 senderDone 通道發送一個 true 訊號以指示完成。
  3. 接收器偵測到ch通道已關閉。
  4. 接收器退出其 for-range 迴圈。

完成(t=302-303ms)

  1. 主協程收到senderDone的訊號並停止等待。
  2. 主協程開始等待來自 receiveDone 的訊號。
  3. 接收器向receiverDone通道發送完成訊號。
  4. 主協程接收訊號並列印:
    • 「所有操作完成!」.
  5. 程式退出。

緩衝通道

為什麼我們需要緩衝通道?
無緩衝的通道會阻塞傳送方和接收方,直到另一方準備好為止。當需要高頻通訊時,無緩衝的通道可能會成為瓶頸,因為兩個 goroutine 必須暫停來交換資料。

緩衝通道屬性:

  1. FIFO(先進先出,類似隊列)
  2. 固定大小,建立時設定
  3. 緩衝區已滿時阻止發送者
  4. 當緩衝區為空時阻塞接收器

Understanding Goroutines and Channels in Golang with Intuitive Visuals

我們看到它的實際效果:

package main

import (
    "fmt"
    "time"
)

func downloadFile(filename string) {
    fmt.Printf("Starting download: %s\n", filename)
    // Simulate file download with sleep
    time.Sleep(2 * time.Second)
    fmt.Printf("Finished download: %s\n", filename)
}

func main() {
    fmt.Println("Starting downloads...")

    startTime := time.Now()

    downloadFile("file1.txt")
    downloadFile("file2.txt")
    downloadFile("file3.txt")

    elapsedTime := time.Since(startTime)

    fmt.Printf("All downloads completed! Time elapsed: %s\n", elapsedTime)
}
登入後複製
登入後複製
登入後複製
登入後複製
登入後複製

輸出(在取消註解 ch

Understanding Goroutines and Channels in Golang with Intuitive Visuals

為什麼它沒有阻塞主協程?

  1. 緩衝通道允許發送至其容量而不阻塞發送者。

  2. 通道的容量為 2,這表示它在阻塞之前可以在緩衝區中保存兩個值。

  3. 緩衝區已經滿了「第一」和「第二」。由於沒有並發接收者來使用這些值,因此發送操作會無限期地阻塞。

  4. 因為主 goroutine 也負責發送,並且沒有其他活動的 goroutine 從通道接收值,所以程式在嘗試發送第三條訊息時陷入死鎖。

取消註解第三則訊息會導致死鎖,因為容量現在已滿,第三則訊息將阻塞,直到緩衝區釋放。

Understanding Goroutines and Channels in Golang with Intuitive Visuals

何時使用緩衝通道與非緩衝通道

Aspect Buffered Channels Unbuffered Channels
Purpose For decoupling sender and receiver timing. For immediate synchronization between sender and receiver.
When to Use - When the sender can proceed without waiting for receiver. - When sender and receiver must synchronize directly.
- When buffering improves performance or throughput. - When you want to enforce message-handling immediately.
Blocking Behavior Blocks only when buffer is full. Sender blocks until receiver is ready, and vice versa.
Performance Can improve performance by reducing synchronization. May introduce latency due to synchronization.
Example Use Cases - Logging with rate-limited processing. - Simple signaling between goroutines.
- Batch processing where messages are queued temporarily. - Hand-off of data without delay or buffering.
Complexity Requires careful buffer size tuning to avoid overflows. Simpler to use; no tuning needed.
Overhead Higher memory usage due to the buffer. Lower memory usage; no buffer involved.
Concurrency Pattern Asynchronous communication between sender and receiver. Synchronous communication; tight coupling.
Error-Prone Scenarios Deadlocks if buffer size is mismanaged. Deadlocks if no goroutine is ready to receive or send.

重點

使用 緩衝 通道如果:

  1. 你需要解耦發送者和接收者的時間。
  2. 批次或排隊訊息可以提高效能。
  3. 當緩衝區已滿時,應用程式可以容忍處理訊息的延遲。

使用 無緩衝 通道,如果:

  1. goroutines 之間的同步至關重要。
  2. 您想要簡單並立即傳遞資料。
  3. 傳送者和接收者之間的互動必須即時發生。

這些基礎知識為更高階的概念奠定了基礎。在我們即將發布的帖子中,我們將探討:

下一篇:

  1. 並發模式
  2. 互斥與記憶體同步

請繼續關注我們,我們將繼續加深對 Go 強大並發功能的理解!

Understanding Goroutines and Channels in Golang with Intuitive Visuals

以上是透過直覺的視覺效果了解 Golang 中的 Goroutines 和 Channel的詳細內容。更多資訊請關注PHP中文網其他相關文章!

本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

記事本++7.3.1

記事本++7.3.1

好用且免費的程式碼編輯器

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

禪工作室 13.0.1

禪工作室 13.0.1

強大的PHP整合開發環境

Dreamweaver CS6

Dreamweaver CS6

視覺化網頁開發工具

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)

熱門話題

Java教學
1654
14
CakePHP 教程
1413
52
Laravel 教程
1306
25
PHP教程
1252
29
C# 教程
1225
24
Golang的目的:建立高效且可擴展的系統 Golang的目的:建立高效且可擴展的系統 Apr 09, 2025 pm 05:17 PM

Go語言在構建高效且可擴展的系統中表現出色,其優勢包括:1.高性能:編譯成機器碼,運行速度快;2.並發編程:通過goroutines和channels簡化多任務處理;3.簡潔性:語法簡潔,降低學習和維護成本;4.跨平台:支持跨平台編譯,方便部署。

Golang和C:並發與原始速度 Golang和C:並發與原始速度 Apr 21, 2025 am 12:16 AM

Golang在並發性上優於C ,而C 在原始速度上優於Golang。 1)Golang通過goroutine和channel實現高效並發,適合處理大量並發任務。 2)C 通過編譯器優化和標準庫,提供接近硬件的高性能,適合需要極致優化的應用。

Golang vs. Python:主要差異和相似之處 Golang vs. Python:主要差異和相似之處 Apr 17, 2025 am 12:15 AM

Golang和Python各有优势:Golang适合高性能和并发编程,Python适用于数据科学和Web开发。Golang以其并发模型和高效性能著称,Python则以简洁语法和丰富库生态系统著称。

Golang vs. Python:性能和可伸縮性 Golang vs. Python:性能和可伸縮性 Apr 19, 2025 am 12:18 AM

Golang在性能和可擴展性方面優於Python。 1)Golang的編譯型特性和高效並發模型使其在高並發場景下表現出色。 2)Python作為解釋型語言,執行速度較慢,但通過工具如Cython可優化性能。

表演競賽:Golang vs.C 表演競賽:Golang vs.C Apr 16, 2025 am 12:07 AM

Golang和C 在性能競賽中的表現各有優勢:1)Golang適合高並發和快速開發,2)C 提供更高性能和細粒度控制。選擇應基於項目需求和團隊技術棧。

Golang的影響:速度,效率和簡單性 Golang的影響:速度,效率和簡單性 Apr 14, 2025 am 12:11 AM

goimpactsdevelopmentpositationality throughspeed,效率和模擬性。 1)速度:gocompilesquicklyandrunseff,IdealforlargeProjects.2)效率:效率:ITScomprehenSevestAndardArdardArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdEcceSteral Depentencies,增強的Depleflovelmentimency.3)簡單性。

C和Golang:表演至關重要時 C和Golang:表演至關重要時 Apr 13, 2025 am 12:11 AM

C 更適合需要直接控制硬件資源和高性能優化的場景,而Golang更適合需要快速開發和高並發處理的場景。 1.C 的優勢在於其接近硬件的特性和高度的優化能力,適合遊戲開發等高性能需求。 2.Golang的優勢在於其簡潔的語法和天然的並發支持,適合高並發服務開發。

Golang和C:性能的權衡 Golang和C:性能的權衡 Apr 17, 2025 am 12:18 AM

Golang和C 在性能上的差異主要體現在內存管理、編譯優化和運行時效率等方面。 1)Golang的垃圾回收機制方便但可能影響性能,2)C 的手動內存管理和編譯器優化在遞歸計算中表現更為高效。

See all articles