个人笔记
package main import ( "fmt" "time" ) type People struct { Name string `json:"name"` Age int `json:"age"` } var channum = 10 func main() { var peoples, peopleb []People for i := 0; i < 100; i++ { peoples = append(peoples, InitPeople("a", i)) peopleb = append(peopleb, InitPeople("b", i)) } begin1 := time.Now().Unix() DoSomething1(peoples) end1 := time.Now().Unix() fmt.Println("-------1-------", end1-begin1) //方法一,类似读写,不需阻塞 begin2 := time.Now().Unix() DoSomething2(peopleb) end2 := time.Now().Unix() fmt.Println("-------2-------", end2-begin2) //时间为0,开启协程,协程在后台运行,方法在后台执行 time.Sleep(time.Second * 10) //用于阻塞方法二,暂时挂起主线程,让协程跑完,缺点是时间不好控制 // select {} //用于阻塞方法二,这里有个问题就是,select{}会一直阻塞,当方法二运行完,所有协程关闭,select{}无法检测到协程,就会报错 } func InitPeople(name string, age int) People { var people People people.Name = name people.Age = age return people } /*---------------------方法一-----------------------*/ func DoSomething1(peoples []People) { ch := ChanNum(channum) defer close(ch) for _, people := range peoples { ch <- people } } func ChanNum(num int) chan<- People { ch := make(chan People) for i := 0; i < num; i++ { go func() { for people := range ch { ReadPeople(people) } }() } return ch } func ReadPeople(people People) { fmt.Println(people.Name, people.Age) time.Sleep(time.Second * 1) } /*---------------------方法二-----------------------*/ func DoSomething2(peoples []People) { peopleArray := make([][]People, channum) for i := 0; i < channum; i++ { peopleArray[i] = make([]People, 0) } for i := range peoples { peopleArray[i%channum] = append(peopleArray[i%channum], peoples[i]) } for i := 0; i < channum; i++ { go ReadPeoples(peopleArray[i]) } } func ReadPeoples(peoples []People) { for _, people := range peoples { ReadPeople(people) } }