CodePudding user response:
Judgement is prime is not playing so wellLogic has a problem, no ready-made code, see red part
Func putNum (numChan chan int, n int) {
For I:=2; i <=n; I++ {
NumChan & lt; -i
FMT. Println (I, "has been in the pipeline")
}
Close (numChan)
FMT. Println (" numChan closed ")
}
Func solve (numChan chan int, resultChan chan int, exitChan chan bool) {
//time. Sleep (time. Microsecond)
For {
Num, ok:=& lt; - numChan
//can't take the data out, said the current coroutines task to complete, could leave
if ! Ok {
Break
}
Flag:=true
For I:=2; iIf I num %==0 {
Flag=false
Break
}
}
The if flag {
ResultChan & lt; - num
FMT. Println (" get "of prime num)
}
}
//tell the other coroutines, coroutines mission completed
ExitChan & lt; - true
FMT. Println (" a collaborators process took less than data and exit ")
}
Func main () {
NumChan:=make (chan int, 1000)
ResultChan:=make (chan int, 1000)
ExitChan:=make (chan bool, 8)
Go putNum numChan, (8000)
//open 8 collaborators cheng
For I:=0; i <8; I++ {
Go solve (numChan resultChan, exitChan)
}
//blocking the main thread, wait for after all coroutines work
Go func () {
For I:=0; i <8; I++ {
//if there is no desirable will wait
<- exitChan
}
//when after eight are close collaborators cheng can close resultChan
Close (resultChan)
FMT. Println (" resultChan closed ")
} ()
//remove the result here can be used for - range, although resultChan is closed by coroutines,
//here, but the main thread running all coroutines have to complete the task, when the resultChan must be shut down
For value:=range resultChan {
FMT. Println (value, "is a prime number")
}
FMT. Println (" the main thread to exit the ")
}
CodePudding user response:
17-29 lines, ~ ~ zha don't change colorCodePudding user response: