问题描述: 生产者进程生产产品,消费者进程消费产品。为使生产者和消费者进程并发进行,在二者之间设置有n个缓冲区的缓冲池,生产者每生产一个产品就放入一个缓冲区,缓冲池满时生产者进程将阻塞。同理消费者每次从缓冲区取走产品。,缓冲池空时消费者进程会阻塞。
方法一:使用mutex互斥锁
package main
import (
"fmt"
"sync"
"time"
)
var n, nextp = 10, 1 // 缓冲区大小
var buf []int // 缓冲区
var mutex sync.Mutex = sync.Mutex{}
func producer() {
for {
mutex.Lock()
// 缓冲区满则阻塞
for len(buf) == n {
mutex.Unlock()
for len(buf) == n {
}
mutex.Lock()
}
buf = append(buf, nextp)
print(buf, true)
mutex.Unlock()
}
}
func consumer() {
for {
mutex.Lock()
// 缓冲区空则阻塞
for len(buf) == 0 {
mutex.Unlock()
for len(buf) == 0 {
}
mutex.Lock()
}
buf = buf[:len(buf)-1]
print(buf, false)
mutex.Unlock()
}
}
// 显示同步过程
func print(buf []int, role bool) {
if role {
fmt.Println("produced an item, the buf = ", buf)
} else {
fmt.Println("consumed an item, the buf = ", buf)
}
}
func main() {
buf = make([]int, 0)
go producer()
go consumer()
time.Sleep(3 * time.Millisecond)
}
方法二:使用管道
package main
import (
"fmt"
"time"
)
var n = 10 // 缓冲区大小
var ch chan int // 缓冲区
var nextp, nextc = 1, 1
func consumer() {
for {
nextc = <-ch
print(false, nextc)
}
}
func producer() {
for {
ch <- nextp
print(true, nextp)
nextp++
}
}
func print(role bool, item int) {
if role {
fmt.Println("produced an item ", item)
} else {
fmt.Println("consumed an item ", item)
}
}
func main() {
ch = make(chan int, n)
go producer()
go consumer()
time.Sleep(3 * time.Millisecond)
}