需求:获取数组数据,对数据的原始数据逐个进行处理,后返回处理完的数据
目标:对列表数据进行逐个goroutine并发处理,再用select整合,返回数据
type money_per struct{ id int name string money float64 } type MoneyHandler interface { BatchDeal(m money_per) } type MoneyHandlerImpl struct { } func getMoneyHandler() MoneyHandler { return &MoneyHandlerImpl{} } var moneyPers = make([]money_per, 10) var mchan = make(chan money_per, 100) //初始化 func init() { for i :=0; i<10 ;i++ { var moneyPer = money_per{i, "ww"+strconv.Itoa(i), float64(i)} moneyPers[i] = moneyPer } } //业务处理 func (monnryHandler MoneyHandlerImpl)BatchDeal(m money_per) { m.money +=11.0 time.Sleep(time.Second) mchan <- m } func main() { fmt.Println(moneyPers, cap(moneyPers), len(moneyPers)) t1 := time.Now() moneyHandler := getMoneyHandler() for mm := range moneyPers{ fmt.Println(moneyPers[mm]) go moneyHandler.BatchDeal(moneyPers[mm]) } elapsed0 := time.Since(t1) fmt.Println("App elapsed0: ", elapsed0) rm := make([]money_per,10) for i :=0; i<10 ;i++ { //m := <-mchan //rm[m.id] = m //fmt.Println(m) select { // select轮询机制 case m := <- mchan: fmt.Println(m) rm[m.id] = m } } elapsed := time.Since(t1) fmt.Println("App elapsed: ", elapsed) }
有疑问加站长微信联系(非本文作者)