Golang 程序使用单向通道将 1 到 10 之间的整数发送到接收函数

go programmingserver side programmingprogramming

在这篇 Go 语言文章中,我们将使用单向通道将 1 到 10 之间的整数发送到接收通道。我们将使用一个基本通道、一个具有固定容量的缓冲通道以及使用 select 语句进行非阻塞通道操作。

语法

ch := make (chan int)

创建无缓冲通道

Value := <-ch

从通道接收值

select {
case ch <- value:
    // 可以发送到通道时执行的代码
default:
    // 无法发送到通道时执行的代码(通道已满)
}

使用 select 语句进行非阻塞通道操作操作

算法

  • 为了在发送方和接收方 goroutine 之间进行通信,创建一个 int 通道。

  • 创建一个名为"sendNumbers"的函数,使用参数将 1 到 10 的数字发送到通道 (ch)。

  • 要从 1 迭代到 10,请使用循环。在循环中使用 - 运算符将每个整数传输到通道。

  • 创建函数"receiveNumbers",它接受参数 ch 并从通道接收和输出整数。

  • 直到通道关闭,使用循环和 range 关键字对其进行迭代。

  • 从通道中获取每个整数并在循环内打印。

  • 在主函数()中 -

    • 创建一个容量为 5 的 int 类型缓冲通道。

    • 启动实现"sendNumbers"函数的"goroutine",将通道作为参数传递。

    • 调用"receiveNumbers"方法时将通道用作参数。

  • 发送器 goroutine 将向通道发送整数,而接收器 goroutine 将在程序运行时同时接收和输出这些整数。

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

此示例包括设置基本通道并逐个发送整数一个到接收函数。这里发送者进入例程,将 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) // 暂停以进行演示
   }
   close(ch)
}

func receiveNumbers(ch <-chan int) {
   for num := range ch {
      fmt.Println("Received:", num)
      time.Sleep(time.Millisecond * 500) // 暂停以进行演示
   }
}

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 的并发编程模型的强大功能来创建强大、可扩展的应用程序。


相关文章