Home > Blockchain >  calculate maximum in parallel in golang using go routine
calculate maximum in parallel in golang using go routine

Time:09-12

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

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)
}

CodePudding user response:

Second loop expects to receive len(arr)*2 values from ch. while len(arr) values are all thar are send to ch
And will return next value read from the channel for max but not max element.

// 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. This will provide you better learning of channels and inter-go-routine communication

CodePudding user response:

Every time you call <- ch, you read a new value from the channel. 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:

        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
        }
    }
  • Related