使用單向通道將整數 1 到 10 傳送到接收函式的 Go 語言程式


在這篇 Go 語言文章中,我們將使用單向通道將整數 1 到 10 傳送到接收通道。我們將使用基本通道、具有固定容量的緩衝通道,以及使用 select 語句進行非阻塞通道操作。

語法

ch := make (chan int)

建立非緩衝通道

Value := <-ch

虛擬碼

從通道接收值

select {
case ch <- value:
   // Code to execute when sending to the channel is possible
default:
   // Code to execute when sending to the channel is not possible (channel full)
}

使用 select 語句進行非阻塞通道操作

演算法

  • 為了在傳送方和接收方 goroutine 之間進行通訊,建立一個 int 型別的通道。

  • 建立一個名為 “sendNumbers” 的函式,該函式使用引數將數字 1 到 10 傳送到通道 (ch)。

  • 要迭代 1 到 10,請使用迴圈。在迴圈內部使用 <- 運算子將每個整數傳送到通道。

  • 建立函式 “receiveNumbers”,它接受引數 ch 並從通道接收並輸出整數。

  • 在通道關閉之前,使用迴圈和 range 關鍵字對其進行迭代。

  • 從通道中獲取每個整數並在迴圈內列印它。

  • 在 main 函式() 中 -

    • 建立一個容量為 5 的 int 型別的緩衝通道。

    • 啟動實現 “sendNumbers” 函式的 “goroutine”,並將通道作為引數傳遞。

    • 在呼叫 “receiveNumbers” 方法時,使用通道作為引數。

  • 傳送方 goroutine 將整數傳送到通道,而接收方 goroutine 將併發接收並輸出這些整數,同時程式執行。

示例 1:使用基本通道通訊

此示例包括設定基本通道並將整數逐個傳送到接收函式。這裡,傳送方 goroutine 將整數 1 到 10 傳送到通道,接收方 goroutine 接收並列印它。

package main

import "fmt"

func sendNumbers(ch chan<- int) {
   for i := 1; i <= 10; i++ {
      ch <- i
   }
   close(ch)
}

func receiveNumbers(ch <-chan int) {
   for num := range ch {
      fmt.Println(num)
   }
}

func main() {
   ch := make(chan int)
   go sendNumbers(ch)
   receiveNumbers(ch)
}

輸出

1
2
3
4
5
6
7
8
9
10

示例 2:使用具有固定容量的緩衝通道

此示例涉及設定具有固定容量的緩衝通道,並在接收函式開始處理它們之前一次傳送多個整數。我們已將通道的容量定義為 5,這意味著傳送方可以在不阻塞的情況下發送 5 個整數。

package main

import "fmt"

func sendNumbers(ch chan<- int) {
   for i := 1; i <= 10; i++ {
      ch <- i
   }
   close(ch)
}

func receiveNumbers(ch <-chan int) {
   for num := range ch {
      fmt.Println(num)
   }
}

func main() {
   ch := make(chan int, 5) 
   go sendNumbers(ch)
   receiveNumbers(ch)
}

輸出

1
2
3
4
5
6
7
8
9
10

示例 3:使用 select 語句進行非阻塞通道操作

此方法使用 select 語句和容量範圍為 3 的緩衝通道來處理操作。

package main

import (
   "fmt"
   "time"
)

func sendNumbers(ch chan<- int) {
   for i := 1; i <= 10; i++ {
      select {
      case ch <- i:
         fmt.Println("Sent:", i)
      default:
         fmt.Println("Channel is full!")
      }
      time.Sleep(time.Millisecond * 700) // Pause for demonstration purposes
   }
   close(ch)
}

func receiveNumbers(ch <-chan int) {
   for num := range ch {
      fmt.Println("Received:", num)
      time.Sleep(time.Millisecond * 500) // Pause for demonstration purposes
   }
}

func main() {
   ch := make(chan int, 3)
   go sendNumbers(ch)
   receiveNumbers(ch)
}

輸出

Sent: 1 
Received: 1 
Sent: 2 
Received: 2 
Sent: 3 
Received: 3 
Sent: 4 
Received: 4 
Sent: 5 
Received: 5 
Sent: 6 
Received: 6 
Sent: 7 
Received: 7 
Sent: 8 
Received: 8 
Sent: 9 
Received: 9 
Sent: 10 
Received: 10 

結論

在本文中,我們討論了三種不同的方法,用於透過單向通道將 1 到 10 的整數傳輸到接收函式。使用這些方法,您可以利用 Go 併發程式設計模型的強大功能來建立健壯且可擴充套件的應用程式。

更新於: 2023 年 7 月 5 日

74 次檢視

啟動您的 職業生涯

透過完成課程獲得認證

開始
廣告

© . All rights reserved.