GO 并发 限时5秒,使用多个goroutine查找切片中是否存在给定的值
假设有一个超长的切片,切片的元素类型为int,切片中的元素为乱序排序。限时5秒,使用多个goroutine查找切片中是否存在给定的值,在查找到目标值或者超时后立刻结束所有goroutine的执行。比如,切片 [23,32,78,43,76,65,345,762,……915,86],查找目标值为 345 ,如果切片中存在,则目标值输出”Found it!”并立即取消仍在执行查询任务的goroutine。如果在超时时间未查到目标值程序,则输出”Timeout!Not Found”,同时立即取消仍在执行的查找任务的goroutine。
package main
import (
"context"
"fmt"
"sync"
"time"
)
func search(ctx context.Context, wg *sync.WaitGroup, slice []int, target int, foundChan chan<- bool, int2 int) {
fmt.Println(int2)
defer wg.Done()
for _, value := range slice {
select {
case <-ctx.Done():
return
default:
if value == target {
foundChan <- true
return
}
}
}
}
func main() {
slice := []int{23, 32, 78, 43, 76, 65, 345, 762, 915, 86} // 示例切片
target := 345 // 查找目标值
timeout := 60 * time.Second // 超时时间
ctx, cancel := context.WithTimeout(context.Background(), timeout)
defer cancel()
var wg sync.WaitGroup
foundChan := make(chan bool, 1)
// 分割切片并启动多个goroutine
chunkSize := len(slice) / 4 // 假设我们使用4个goroutine
for i := 0; i < 4; i++ {
wg.Add(1)
start := i * chunkSize
end := (i + 1) * chunkSize
if i == 3 {
end = len(slice) // 确保最后一个goroutine处理剩余的所有元素
}
go search(ctx, &wg, slice[start:end], target, foundChan, i)
}
//found := false
select {
case <-foundChan:
fmt.Println("Found it!")
case <-ctx.Done():
fmt.Println("Timeout! Not Found")
}
cancel() // 取消所有goroutine
wg.Wait() // 等待所有goroutine完成
}
本作品采用《CC 协议》,转载必须注明作者和本文链接