packagemainimport("fmt""strconv""sync""time")varmmap[string]stringtypeDatastruct{KeystringValuestring}funcworker(queuechanData,finishedchanstruct{}){for{d,more:=<-queueif!more{fmt.Println("Stopping worker due to closed channel")break}//fmt.Print(".")m[d.Key]=d.Value}finished<-struct{}{}}funcmain(){ConcurrentSender:=100m=make(map[string]string)done:=[]chanstruct{}{}mutex:=sync.Mutex{}start:=time.Now()fori:=0;i<ConcurrentSender;i++{d:=make(chanstruct{})done=append(done,d)gofunc(donechanstruct{},mut*sync.Mutex,indint){forj:=0;j<100;j++{mut.Lock()m[strconv.Itoa(j)]=strconv.Itoa(j+(1000*(ind+1)))mut.Unlock()}done<-struct{}{}}(d,&mutex,i)}for_,d:=rangedone{_=<-d}duration:=time.Since(start)fmt.Printf("\nMutex Solution took %s",duration)m=make(map[string]string)done=[]chanstruct{}{}queue:=make(chanData)// start of the worker go routinefinished:=make(chanstruct{})goworker(queue,finished)start=time.Now()fori:=0;i<ConcurrentSender;i++{d:=make(chanstruct{})done=append(done,d)gofunc(queuechanData,donechanstruct{},indint){fori:=0;i<100;i++{// Write element to queuequeue<-Data{Key:strconv.Itoa(i),Value:strconv.Itoa(i+(100*(ind+1)))}}done<-struct{}{}}(queue,d,i)}for_,d:=rangedone{_=<-d}duration=time.Since(start)close(queue)_=<-finishedfmt.Printf("Channel Solution took %s",duration)}
从复杂度和开销来说 Channel 要比 Mutex 昂贵。虽然官方说:
"Don't communicate by sharing memory; instead, share memory by communicating." (“不要通过共享内存进行通信,而是通过通信共享内存。”)