需求

使用golang协程,并限制协程数量。

package main

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

type Report struct {
	Name string `json:"name"`
}

func main() {

	c := make(chan struct{}, 2)
	cReports := make(chan []Report, 1)
	wg := sync.WaitGroup{}

	defer close(c)
	defer close(cReports)

	for i := 0; i < 80; i++ {
		c <- struct{}{}
		wg.Add(1)
		go func(i int) {
			wg.Done()
			reports := make([]Report, 0)
			for j := 0; j < rand.Intn(500); j++ {
				for k := 0; k < rand.Intn(500); k++ {
					reports = append(reports, Report{Name: fmt.Sprintf("i-%d-j-%d-k-%d", i, j, k)})
				}
				fmt.Println("send reports ", reports)
			}

			//time.Sleep(time.Second)
			<-c
			cReports <- reports
		}(i)
	}

	wg.Wait()

Recv:
	for {
		select {
		case r, ok := <-cReports:
			fmt.Println("r,ok", r, ok)
		default:
			fmt.Println("recv finish")
			break Recv
		}
	}

	fmt.Println("finish")
}

问题注意

<-ccReports <- reportscReports <- reportsfor j := 0; j < rand.Intn(500); j++ {fatal error: all goroutines are asleep - deadlock!

报错内容

fatal error: all goroutines are asleep - deadlock!