登录
首页 >  Golang >  Go问答

在取消上下文前不可能同时使用 goroutine 查找最大值

来源:stackoverflow

时间:2024-03-05 15:30:27 475浏览 收藏

亲爱的编程学习爱好者,如果你点开了这篇文章,说明你对《在取消上下文前不可能同时使用 goroutine 查找最大值》很感兴趣。本篇文章就来给大家详细解析一下,主要介绍一下,希望所有认真读完的童鞋们,都有实质性的提高。

问题内容

我已经成功地为 compute 调用的 findmax 制作了一个没有 goroutines 的同步解决方案。

package main

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

func findmax(ctx context.context, concurrency int) uint64 {
    var (
        max uint64 = 0
        num uint64 = 0
    )

    for i := 0; i < concurrency; i++ {
        num = compute()

        if num > max {
            max = num
        }
    }

    return max
}

func compute() uint64 {
    // note: this is a mock implementation of the blocking operation.
    
    time.sleep(time.duration(rand.int63n(100)) * time.millisecond)
    return rand.uint64()
}

func main() {
    maxduration := 2 * time.second
    concurrency := 10

    ctx, cancel := context.withtimeout(context.background(), maxduration)
    defer cancel()

    max := findmax(ctx, concurrency)
    fmt.println(max)
}

https://play.golang.org/p/lyxrntdtnci

当我尝试使用 goroutine 使用 findmax 重复调用 compute 函数时,使用尽可能多的 goroutine,直到上下文 ctx 被调用者 main 函数取消。我每次都得到 0,而不是灌浆计算函数调用的预期最大值。我尝试了不同的方法来做到这一点,但大多数时候都陷入僵局。

package main

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

func findMax(ctx context.Context, concurrency int) uint64 {
    var (
        max uint64 = 0
        num uint64 = 0
    )

    for i := 0; i < concurrency; i++ {
        select {
        case <- ctx.Done():
            return max
        default:
            go func() {
                num = compute()
                if num > max {
                    max = num
                }
            }()
        }
    }

    return max
}

func compute() uint64 {
    // NOTE: This is a MOCK implementation of the blocking operation.
    
    time.Sleep(time.Duration(rand.Int63n(100)) * time.Millisecond)
    return rand.Uint64()
}

func main() {
    maxDuration := 2 * time.Second
    concurrency := 10

    ctx, cancel := context.WithTimeout(context.Background(), maxDuration)
    defer cancel()

    max := findMax(ctx, concurrency)
    fmt.Println(max)
}

https://play.golang.org/p/3fffq2xlxae


正确答案


您的程序有多个问题:

  1. 您正在生成多个对共享变量进行操作的 goroutine,即 maxnum,因为它们不受保护(例如通过互斥锁),从而导致数据争用。
  2. 这里 num 被每个工作 goroutine 修改,但它应该是工作进程本地的,否则计算的数据可能会丢失(例如,一个工作 goroutine 计算结果并将其存储在 num 中,但紧接着第二个工作进程计算并替换 num 的值)。
num = compute // should be "num := compute"
  1. 您不会等待每个 goroutine 完成其计算,并且可能会导致不正确的结果,因为即使上下文未取消,也不会考虑每个工人的计算。使用 sync.waitgroup 或通道来修复此问题。

下面是一个示例程序,可以解决代码中的大多数问题:

package main

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

type result struct {
    sync.RWMutex
    max uint64
}

func findMax(ctx context.Context, workers int) uint64 {
    var (
        res = result{}
        wg  = sync.WaitGroup{}
    )

    for i := 0; i < workers; i++ {
        select {
        case <-ctx.Done():
            // RLock to read res.max
            res.RLock()
            ret := res.max
            res.RUnlock()
            return ret
        default:
            wg.Add(1)
            go func() {
                defer wg.Done()
                num := compute()

                // Lock so that read from res.max and write
                // to res.max is safe. Else, data race could
                // occur.
                res.Lock()
                if num > res.max {
                    res.max = num
                }
                res.Unlock()
            }()
        }
    }

    // Wait for all the goroutine to finish work i.e., all
    // workers are done computing and updating the max.
    wg.Wait()

    return res.max
}

func compute() uint64 {
    rnd := rand.Int63n(100)
    time.Sleep(time.Duration(rnd) * time.Millisecond)
    return rand.Uint64()
}

func main() {
    maxDuration := 2 * time.Second
    concurrency := 10

    ctx, cancel := context.WithTimeout(context.Background(), maxDuration)
    defer cancel()

    fmt.Println(findMax(ctx, concurrency))
}

正如 @brits 在评论中指出的那样,当上下文被取消时,请确保停止这些工作协程以停止处理(如果可能),因为不再需要它了。

到这里,我们也就讲完了《在取消上下文前不可能同时使用 goroutine 查找最大值》的内容了。个人认为,基础知识的学习和巩固,是为了更好的将其运用到项目中,欢迎关注golang学习网公众号,带你了解更多关于的知识点!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>