MST
星途 面试题库

面试题:Go中通道与Goroutine如何实现简单的生产者消费者模型

请用Go语言编写代码,实现一个简单的生产者消费者模型,生产者每秒生成一个数字并发送到通道,消费者从通道接收数字并打印。要求清晰展示通道与Goroutine的协作。
18.5万 热度难度
编程语言Go

知识考点

AI 面试

面试题答案

一键面试
package main

import (
    "fmt"
    "time"
)

func producer(ch chan int) {
    for i := 0; ; i++ {
        ch <- i
        time.Sleep(time.Second)
    }
}

func consumer(ch chan int) {
    for num := range ch {
        fmt.Println("Received:", num)
    }
}

func main() {
    ch := make(chan int)

    go producer(ch)
    go consumer(ch)

    select {}
}

上述代码解释:

  1. producer函数:每秒向通道ch发送一个递增的数字。
  2. consumer函数:从通道ch接收数字并打印。
  3. main函数:创建通道ch,启动生产者和消费者的Goroutine。最后使用select {}使主Goroutine不退出。