packagemainimport("fmt""os""time")const(MAX_REQUEST_NUM=10CMD_USER_POS=1)var(savechanboolquitchanboolreqchan*Request)typeRequeststruct{CmdIdint16Datainterface{}}typeUserPosstruct{xint16yint16}funcinit(){req=make(chan*Request,MAX_REQUEST_NUM)save=make(chanbool)quit=make(chanbool)}funcsaveGame(){fmt.Println("DosomethingwithSaveGame")quit<-true}funconReq(r*Request){pos:=r.Data.(UserPos)fmt.Println(r.CmdId,pos)}funchandler(){for{select{case_,ok:=<-save://fmt.Println("saving.......")ifok{saveGame()}else{fmt.Println("channelemptyorclosed")}caser,ok:=<-req:ifok{onReq(r)}else{fmt.Println("reqchanclosed")os.Exit(0)}}}}funcmain(){//为什么要有quit,quit的作用是什么newReq:=&Request{CmdId:CMD_USER_POS,Data:UserPos{x:10,y:20,},}gohandler()req<-newReqtime.Sleep(time.Millisecond*200)save<-trueclose(req)<-quit}上面这段代码里,如果注释掉quit<-true和<-quit结果只能打印1{1020},若保留,则打印1{1020}DosomethingwithSaveGamereqchanclosed没太看懂这里quit的作用。我的想法是,正常给save<-true之后,应该打印DosomethingwithSaveGame啊关闭req之后,也该有reqchanclosed打印啊看来还是理解不到位,go小白,辛苦大神指导下
一只斗牛犬
jeck猫
相关分类