Skip to content

Latest commit

 

History

History
75 lines (52 loc) · 1.71 KB

q017.md

File metadata and controls

75 lines (52 loc) · 1.71 KB

多协程查询切片问题

题目

假设有一个超长的切片,切片的元素类型为int,切片中的元素为乱序排序。限时5秒,使用多个goroutine查找切片中是否存在给定的值,在查找到目标值或者超时后立刻结束所有goroutine的执行。

比如,切片 [23,32,78,43,76,65,345,762,......915,86],查找目标值为 345 ,如果切片中存在,则目标值输出"Found it!"并立即取消仍在执行查询任务的goroutine

如果在超时时间未查到目标值程序,则输出"Timeout!Not Found",同时立即取消仍在执行的查找任务的goroutine

答案: https://mp.weixin.qq.com/s/GhC2WDw3VHP91DrrFVCnag

自己的答案:

// You can edit this code!
// Click here and start typing.
package main

import (
	"fmt"
	"math"
	"time"
)

var s = []int{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17}
var stopAll = false
var foundIt = make(chan struct{}, 1)

func SearchInRange(val int, start int, length int) {
	fmt.Println(val, start, length, "go-inside")
	for i := start; i < start+length; i++ {
		fmt.Println(i, length)
		if i >= len(s) || stopAll {
			fmt.Println(val, start, length, "go-quit")
			return
		}
		if s[i] == val {
			foundIt <- struct{}{}
			stopAll = true
			return
		}
	}
}

func main() {
	var maxG = 5
	var val = 8
	var groupLen = int(math.Ceil(float64(len(s)) / float64(maxG)))
	for i := 0; i < maxG; i++ {
		fmt.Println(val, i*groupLen, groupLen, "go")
		go SearchInRange(val, i*groupLen, groupLen)
	}
	var timeoutX = time.NewTimer(time.Second * 3)
	select {
	case <-timeoutX.C:
		fmt.Println("Timeout!Not Found")
	case <-foundIt:
		fmt.Println("Found It")
	}

	fmt.Println("Hello, 世界")
}