go实现一个简单的生产消费者模型

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

type Buffer struct {
	mutex    sync.Mutex
	notEmpty *sync.Cond
	buff     []int
}

func NewBuffer() *Buffer {
	buf := Buffer{
		buff: make([]int, 0),
	}
	buf.notEmpty = sync.NewCond(&buf.mutex)
	return &buf
}
func (b *Buffer) put(value int) {
	b.mutex.Lock()
	defer b.mutex.Unlock()
	fmt.Printf("生产者放入数据 %v\n", value)
	b.buff = append(b.buff, value)
	b.notEmpty.Broadcast()
}

func (b *Buffer) get() int {
	b.mutex.Lock()
	defer b.mutex.Unlock()
	if len(b.buff) == 0 {
		fmt.Println("缓冲区为空,消费者等待...")
		b.notEmpty.Wait()
	}
	v := b.buff[0]
	b.buff = b.buff[1:]
	fmt.Printf("消费者消费数据: %v\n", v)
	return v
}
func main() {
	buff := NewBuffer()
	wg := sync.WaitGroup{}
	wg.Add(2)
	go func() {
		defer wg.Done()
		for i := 1; i <= 100; i++ {
			buff.put(rand.Int())
			time.Sleep(time.Second * 1)
		}
	}()
	go func() {
		defer wg.Done()
		for i := 1; i <= 100; i++ {
			_ = buff.get()
		}
	}()
	wg.Wait()
}
posted @ 2025-03-31 15:37  seonwee  阅读(6)  评论(0)    收藏  举报