Go生产者-消费者模式

104 阅读1分钟

以下是一个简单的生产者-消费者模式的示例,使用 Go 语言实现:

package main

import (
	"fmt"
	"math/rand"
	"sync"
	"time"
)

const (
	maxJobs   = 10
	numProduc = 5
	numConsu  = 3
)

var wg sync.WaitGroup

func main() {
	jobs := make(chan int, maxJobs)

	// 创建生产者
	for i := 0; i < numProduc; i++ {
		wg.Add(1)
		go producer(jobs, i)
	}

	// 创建消费者
	for i := 0; i < numConsu; i++ {
		wg.Add(1)
		go consumer(jobs, i)
	}

	wg.Wait()
	fmt.Println("All producers and consumers finished.")
}

func producer(jobs chan<- int, id int) {
	defer wg.Done()
	for {
		job := rand.Intn(100) // 产生随机任务
		jobs <- job           // 将任务发送到通道
		fmt.Printf("Producer %d produced job: %d\n", id, job)
		time.Sleep(time.Duration(rand.Intn(3)) * time.Second)
	}
}

func consumer(jobs <-chan int, id int) {
	defer wg.Done()
	for {
		job := <-jobs // 从通道中接收任务
		fmt.Printf("Consumer %d consumed job: %d\n", id, job)
		time.Sleep(time.Duration(rand.Intn(3)) * time.Second)
	}
}

这个示例中,有多个生产者和消费者,它们共享一个通道 jobs,生产者生产随机任务并发送到通道中,消费者从通道中接收任务并消费。生产者和消费者都是通过 goroutine 来实现并发执行的。