用Go写生产者消费者运用Go自带的channel而言是十分容易的。网上也有很多现成的例子
package main
import (
"fmt"
"sync"
)
var (
ch = make(chan int, 10)
finish bool
)
func main() {
var wgp sync.WaitGroup
var wgc sync.WaitGroup
//queue := newQueue(20)
go pro(&wgp, 1)
go pro(&wgp, 2)
go pro(&wgp, 3)
wgp.Add(3)
go cus(&wgc, 1)
go cus(&wgc, 2)
go cus(&wgc, 3)
go cus(&wgc, 4)
go cus(&wgc, 5)
wgc.Add(5)
wgp.Wait()
finish = true
wgc.Wait()
}
func pro(wg *sync.WaitGroup, num int) {
defer wg.Done()
for i := 0; i < 10; i++ {
ch <- num*10 + i
fmt.Println("p", num, ":", num*10+i)
}
}
func cus(wg *sync.WaitGroup, num int) {
defer wg.Done()
for !finish {
fmt.Println("c", num, ":", <-ch)
}
}
但是如果不用channel实现呢,那么就要用到循环队列了
package main
import (
"sync"
"time"
"fmt"
)
type Queue struct {
Cache []int
length int