funcmain() { targetNum := 898982 total := 2000000000 s := GetRandomSlice(total, 200000000, targetNum) t := time.Now() manager := NewManager(250000000) manager.Search(s, targetNum) fmt.Println(manager.Result()) fmt.Printf("find the number of %d, time conumin %v\n", total, time.Since(t)) }
funcGetRandomSlice(sliceLen int, randNum int, targetNum int) []int { tmp := make([]int, sliceLen) rand.Seed(time.Now().UnixNano()) for i := 0; i < sliceLen; i++ { randNum := rand.Intn(randNum) tmp[i] = randNum if randNum == targetNum { fmt.Println("randNum is ", i) } } return tmp }
type Manager struct { s []int targetNum int chunkSize int chunkNum int once sync.Once ctx context.Context cancel func() result chanstring }
funcChunk(total, chunkSize int, f func(part, startIndex, endIndex int)) { if total%chunkSize == 0 { for i := 0; i < total/chunkSize; i++ { e := (i + 1) * chunkSize f(i+1, i*chunkSize, e) } } else { for i := 0; i <= total/chunkSize; i++ { e := (i + 1) * chunkSize if i == (total / chunkSize) { e = i*chunkSize + total%chunkSize } f(i+1, i*chunkSize, e) } } }
func(m *Manager) Worker(part, startIndex, endIndex int) { m.chunkNum++ gofunc() { for i, v := range m.s[startIndex:endIndex] { if v == m.targetNum { m.result <- fmt.Sprintf("Found! At index %d\n", (part-1)*m.chunkSize+i) return } select { case <-m.ctx.Done(): return default: continue } } m.result <- "" return }() }
func(m *Manager) Result() string { var once sync.Once var num int for { select { case <-time.After(time.Second * time.Duration(10)): once.Do(m.cancel) return"Timeout! Not Found" case res := <-m.result: if res != "" { once.Do(m.cancel) return res } num++ if num == m.chunkNum { once.Do(m.cancel) return"All Task Done,Not Found!" } } } }