通过协程查找数组中元素


本文摘自网络,作者,侵删。

给定一个无序数组,求某个数值是否存在数组当中。

正常需要先排序,再二分去做的,不过由于 golang 中是可以很方便就可以起多个协程,所以测试下,多个协程分别查找各自的一段,如果查到就通知其他协程停止查找,当然为了完整性,在程序执行 5 秒,还未找到则停止查找。

package main

import (
    "context"
    "fmt"
    "math"
    "math/rand"
    "time"
)

func generate(size int) []int {

    return rand.Perm(size)
}

func generateTarget(size int) int {

    rand.Seed(time.Now().Unix())

    return int(rand.Int31n(int32(size)))
}

func main() {

    size := math.MaxInt32 / 1000

    arr := generate(size)
    target := generateTarget(size)

    n := len(arr)

    routineCount := 10 // 开 routineCount 个 goroutine

    sp := n / routineCount // 将数组切割成每份 sp 个

    ctx, cancel := context.WithCancel(context.Background()) // 利用 context 的特性

    ch := make(chan int) // 找到结果的通知 chan

    fmt.Println("开始查找")
    for i := 0; i < routineCount; i++ {
        go func(i int, ctx context.Context) {
            curArr := arr[i*sp : (i+1)*sp] // 每次切割一部分

            for _, v := range curArr {

                select {
                case <-ctx.Done(): // 如果通知结束,则终止
                    return
                default: // 其他情况直接去比较
                }
                if v == target {
                    ch <- target // 找到了将消息发送出来
                }
            }
        }(i, ctx)
    }

    fmt.Println("target", target) // 需要找的 targe
    select {
    case t := <-ch:
        fmt.Println("找到了", t)
        cancel() // 找到了,结束所有子 goroutine
    case <-time.After(5 * time.Second): // 有个倒计时
        fmt.Println("未找到")
    }
}

测试了下速度,确实很快


本文来自:简书

感谢作者:追风骚年

查看原文:通过协程查找数组中元素

相关阅读 >>

[Go] Go语言实战-基于websocket浏览器通知的实现

Golang调用cmd命令时如何隐藏dos窗口

分享一个Go json 踩坑记录

ketos 笔记 -- 记 Go hackathon 2017

Golang判断字符串是否为空的方法

Go - 如何解析 json 数据?

Go语言标准库之context

Golang 踩坑时间parse转换后加8小时

Golang array slice操作示例 去重 插入 删除 清空

Go-carbon 1.4.0 版本发布,新增获取世纪和季度开始和结束时间方法

更多相关阅读请进入《Go》频道 >>




打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...