Passing an array as value in a Goroutine function does nothing

Issue

I have something like this:

package main

import (
    "fmt"
)

// Empty2DArray returns a zeroed 2D array.
func Empty2DArray(arraySize int) [][]int {
    emptyArray := make([][]int, arraySize)
    for y := 0; y < arraySize; y++ {
        row := make([]int, arraySize)
        for x := 0; x < arraySize; x++ {
            row[x] = 0
        }
        emptyArray[y] = row
    }
    return emptyArray
}

func DoSomethingWithArray(aSize, threadID int, mapArray [][]int) {

    var start, end int

    switch threadID {
    case 0: // unique thread
        start = 0
        end = aSize
    case 1: // 1 and 2 when using more than 1 and less than 2 threads.
        start = 0
        end = aSize / 2
    case 2:
        start = aSize/2 + 1
        end = aSize
    }

    for j := start; j < end; j++ {
        for i := 0; i < aSize; i++ {
            mapArray[i][j] = 1
        }
    }
}

func main() {

    someArray := Empty2DArray(4)
    DoSomethingWithArray(4, 0, someArray) // this works
    //  go DoSomethingWithArray(4,0,someArray) // this doesnt
    fmt.Println(someArray)
}

If i do this i get nothing new in someArray, just the zeroes i got in the initialization. I’m sure i need a channel to communicate between the goroutines and the receiving array, but I’m clueless.

Any tips?

Thanks!

EDIT: some working code

Solution

When you put go in front of it, it runs it in a separate goroutine (similar to a thread), and the current code path continues – they are running at the same time.

This means, that when you do fmt.Println(someArray), you have no guarantee that DoSomethingWithArray has completed. In this instance, you could use a sync.WaitGroup, to let your current thread wait until the other code has completed:

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

var wg sync.WaitGroup
func main() {
    someArray := Empty2DArray(4)
    wg.Add(1)
    go DoSomethingWithArray(4,0,someArray)
    wg.Wait()
    fmt.Println(someArray)
}

func DoSomethingWithArray(aSize, threadID int, mapArray [][]int) {
    //your code
    wg.Done()
}

Answered By – dave

Answer Checked By – Katrina (GoLangFix Volunteer)

Leave a Reply

Your email address will not be published.