Go: select 實戰指南:協程切換技術

概述

Go 語言的併發編程模型以其簡潔而強大的 goroutine 爲特色。

而 select 語句則是在多個通信操作中選擇一個執行的關鍵工具。

本文將討論如何使用 select 切換協程,通過清晰的示例代碼,幫助讀者掌握這一重要的併發編程技巧。

  1. select 語句的基本結構
package main
import (
	"fmt"
	"time"
)
func main() {
	ch1 := make(chan string)
	ch2 := make(chan string)
	go func() {
		time.Sleep(2 * time.Second)
		ch1 <- "goroutine 1 completed"
	}()
	go func() {
		time.Sleep(1 * time.Second)
		ch2 <- "goroutine 2 completed"
	}()
	select {
	case res := <-ch1:
		fmt.Println(res)
	case res := <-ch2:
		fmt.Println(res)
	}
}
  1. 使用 select 進行超時控制
package main
import (
  "fmt"
  "time"
)
func main() {
  ch := make(chan string)
  go func() {
    time.Sleep(2 * time.Second)
    ch <- "goroutine completed"
  }()
  select {
  case res := <-ch:
    fmt.Println(res)
  case <-time.After(1 * time.Second):
    fmt.Println("Timeout: goroutine not completed within 1 second")
  }
}
  1. 多通道操作與 select 結合
package main
import (
  "fmt"
  "time"
)
func main() {
  ch1 := make(chan string)
  ch2 := make(chan string)
  go func() {
    time.Sleep(2 * time.Second)
    ch1 <- "goroutine 1 completed"
  }()
  go func() {
    time.Sleep(1 * time.Second)
    ch2 <- "goroutine 2 completed"
  }()
  for i := 0; i < 2; i++ {
    select {
    case res := <-ch1:
      fmt.Println(res)
    case res := <-ch2:
      fmt.Println(res)
    }
  }
}
  1. 使用 select 進行非阻塞通信
package main
import (
  "fmt"
  "time"
)
func main() {
  ch := make(chan string)
  select {
  case res := <-ch:
    fmt.Println(res)
  default:
    fmt.Println("No communication yet")
  }
  go func() {
    time.Sleep(1 * time.Second)
    ch <- "goroutine completed"
  }()
  time.Sleep(2 * time.Second)
}
  1. 在 select 中使用 default 語句
package main
import (
  "fmt"
  "time"
)
func main() {
  ch1 := make(chan string)
  ch2 := make(chan string)
  select {
  case res := <-ch1:
    fmt.Println(res)
  case res := <-ch2:
    fmt.Println(res)
  default:
    fmt.Println("No communication yet")
  }
  go func() {
    time.Sleep(2 * time.Second)
    ch1 <- "goroutine 1 completed"
  }()
  time.Sleep(1 * time.Second)
}
  1. 利用 select 處理多路通信
package main
import (
  "fmt"
  "time"
)
func main() {
  ch1 := make(chan string)
  ch2 := make(chan string)
  go func() {
    time.Sleep(2 * time.Second)
    ch1 <- "goroutine 1 completed"
  }()
  go func() {
    time.Sleep(1 * time.Second)
    ch2 <- "goroutine 2 completed"
  }()
  for i := 0; i < 2; i++ {
    select {
    case res := <-ch1:
      fmt.Println(res)
    case res := <-ch2:
      fmt.Println(res)
    }
  }
}

總結

通過本文的討論和示例代碼,對如何使用 select 切換協程有了更深入的理解。

select 是 Go 語言併發編程中的一項強大工具,掌握其使用技巧將有助於讀者更好地處理併發場景,提高代碼的可讀性和可維護性。

在實際項目中,善用 select 將使你的併發代碼更加優雅而高效。

本文由 Readfog 進行 AMP 轉碼,版權歸原作者所有。
來源https://mp.weixin.qq.com/s/PyCqARy-n2kiZQ6h5LldFA