生产者消费者
1个生产者10个消费者 第一种
package program
import (
"fmt"
"testing"
)
func TestProgram(t *testing.T) {
ch := make(chan int)
stop := make(chan int)
go producer(ch)
go consumer(ch, stop)
<-stop
fmt.Println("over")
}
func consumer(ch, stop chan int) {
for i := 0; i < 10; i++ {
go func() {
for {
c, ok := <-ch
if !ok {
stop <- 1
return
}
fmt.Println("current taskid", c)
}
}()
}
}
func producer(ch chan int) {
for i := 0; i < 10000; i++ {
ch <- i
}
close(ch)
}
1个生产者10个消费者 第二种
package program
import (
"fmt"
"sync"
"testing"
)
func TestProgram(t *testing.T) {
ch := make(chan int)
wg := sync.WaitGroup{}
wg.Add(10)
go producer(ch)
go consumer(ch, &wg)
wg.Wait()
fmt.Println("over")
}
func consumer(ch chan int, wg *sync.WaitGroup) {
for i := 0; i < 10; i++ {
go func() {
defer wg.Done()
for c := range ch {
fmt.Println("execute task", c)
}
}()
}
}
func producer(ch chan int) {
for i := 0; i < 10000; i++ {
ch <- i
}
close(ch)
}