Home > other > Beginners, on the return and break to distinguish
Beginners, on the return and break to distinguish
Time:12-01
This is a prime number code, is able to run normally, but when I changed his 14 lines of code by the break for the return, the code to run complains, but although error, is also able to print the correct results first and then prompt error (see picture), could you tell me why to use the return Complains, the feeling in this code break and should have the same effect to return, please teach bosses Package the main The import "FMT" Func putNum (intChan chan int) { For I:=1; i<=80; I++ { IntChan<-i } Close (intChan) } Func primeNum (intChan chan int, primeChan chan int, exitChan chan bool) { For { Var flag bool=true V, ok:=& lt; - intChan if ! Ok { Break } For I:=2; iIf I==0 v % { Flag=false Break } } The if flag { PrimeChan} } ExitChan<- true } Func main () { IntChan:=make (chan int, 800) PrimeChan:=make (chan int, 600) ExitChan:=make (chan bool, 4) Go putNum (intChan) For I:=1; i<=4; I++ { Go primeNum (intChan primeChan, exitChan) } Go func () { For I:=1; i<=4; I++ { <- exitChan } Close (primeChan) Close (exitChan) } () For { V, ok:=& lt; - primeChan if ! Ok { Break } FMT. Println (v) } }
CodePudding user response:
This error is call lock, Reason is because change needs 14 lines break to return after the last number when putNum read after closing intChan, 14 lines primeNum function return directly, not to value the exitChan, result in the main, from exitChan receive four Boolean value operation blocks, cause a deadlock, You can change the Func primeNum (intChan chan int, primeChan chan int, exitChan chan bool) { . ExitChan<- true }
Func primeNum (intChan chan int, primeChan chan int, exitChan chan bool) { Defer func () { ExitChan<- true } () . } Such modifications break for return should be no problem,