1. Calculate the Golang implementation of prime numbers in the range 1 to 100000
Package ConcurrentDemo import (" FMT ""sync") //1-10000000 var start int = 0 // var end int = 1000000 // var end int = 1000000 // End int = 1000 var interval int = 100 var wg sync. waitGroup func calResult(x int) bool {end int = 1000 var interval int = 100 var wg sync. waitGroup func calResult(x int) Max := x/2 + 1 result := true for I := 2; i < max; i++ { if x%i == 0 { result = false break } } return result } func startTask(start, end, Interval int) {// start the task from := make(chan int,10) // start the task from := make(chan int,10) exitChan := make(chan bool,16) // To see if each goroutine has been executed, Resultchan time: = (end-start)/interval // total goroutine fmt.printf ("time:%d \n", time) for I := 1; i <= time; i++ { wg.Add(1) startTemp := (i-1)*interval + start endTemp := i * interval fmt.Printf("startTemp:%d,endTemp:%d \n", startTemp, endTemp) go resolve(startTemp, endTemp, resultChan,exitChan) } wg.Add(1) go func () { for i := 1; i <= time; Wg.Done() in (resultChan) // After all the goroutines have calculated the primes in their range, send them to resultChan. Resultchan}() for v := Range resultChan{fmt.printf ("result:%d \n",v)} fmt.println ("main Finished ") wg.wait ()} func resolve(start, end int, resultChan chan<- int,exitChan chan<- bool) { for i := start; i < end; i++ { if calResult(i) { resultChan <- i } } exitChan <- true fmt.Printf("start:%d,end:%d finished \n", start, end) wg.Done() } func ConcurrentDemoT() { startTask(start, end, interval) }
Results 2.