简体   繁体   English

使用 go 例程在 golang 中并行计算最大值

[英]calculate maximum in parallel in golang using go routine

I am trying to understand concurrency and parallelism.我试图了解并发性和并行性。 I need to calculate the maximum of an array using the go routine, channel wait group, and stored in a shared variable here is the below code getting deadlock, please give direction我需要使用 go 例程,通道等待组来计算数组的最大值,并存储在共享变量中这是下面的代码陷入死锁,请指导

package main

import (
    "fmt"
    "math"
)

func main() {
    arr := []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
    max := math.MinInt32
    ch := make(chan int)
    for i := 0; i < len(arr); i++ {
        go func(i int) {
            ch <- arr[i]
        }(i)
    }
    for i := 0; i < len(arr); i++ {
        if max < <-ch {
            max = <-ch
        }
    }
    fmt.Println(max)
}

Second loop expects to receive len(arr)*2 values from ch .第二个循环期望从ch接收len(arr)*2值。 while len(arr) values are all thar are send to chlen(arr)值都是 thar 发送到ch
And will return next value read from the channel for max but not max element.并将返回从通道读取的下一个值,用于 max 但不是 max 元素。

// Reading from channel twice.
if max < <-ch {
// This is next value after max not max
    max = <-ch
}

Change second loop to将第二个循环更改为

for i := 0; i < len(arr); i++ {
  got := <-ch
    if max < got {
      max = got
    }
}

Suggest : this is not calculating maximum in parallel .建议:这不是并行计算最大值 Channel is read serially here and values compared to a max, as good as ranging over the slice itself.在这里连续读取通道,并将值与最大值进行比较,与切片本身的范围一样好。

You can instead implement DAC based approach to find max of 2 elements in a go-routine and then merge the results, to find the ultimate max.您可以改为实施基于 DAC 的方法,以在 go-routine 中找到最多 2 个元素,然后合并结果,以找到最终的最大值。 This will provide you better learning of channels and inter-go-routine communication这将为您提供更好的渠道学习和日常沟通

Every time you call <- ch , you read a new value from the channel.每次调用<- ch时,都会从通道中读取一个新值。 This means that your code这意味着您的代码

        if max < <-ch {
            max = <-ch
        }

Does not do what you expect.不做你所期望的。

If your channel is fed the values 1 , 2 , ..., then your code will work as follows:如果您的频道输入值12 、 ...,那么您的代码将按如下方式工作:

        if max < <-ch { // Reads value `1`, compares it against `max`
            max = <-ch  // Reads the value `2`, then assigns it to `max`
        }

The reason this leads to a deadlock is that you're reading twice as many values from the channel as you write to it, since for every time through the loop, you're trying to read two values.这导致死锁的原因是您从通道读取的值是写入通道的两倍,因为每次通过循环时,您都在尝试读取两个值。

To solve both problems at once, use a temporary variable:要同时解决这两个问题,请使用临时变量:

    for i := 0; i < len(arr); i++ {
        if value := <-ch; max < value {
            max = value
        }
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM