looping from size of list but some index not called when in goroutine

Issue

i have a dispatcher worker and I loop for the number of jobs from the length of the list , but there are some index not called while looping

    var members = []Member{
        {ID: 1, Is: true},
        {ID: 2, Is: false},
        {ID: 3, Is: true},
    }

    numOfWorker := 2
    var durationDelay time.Duration = 5000

    do, _ := worker.NewDispatcher(numOfWorker)
    ch := make(chan worker.MainJob, len(members))

    go func(jobs int) {
        for i := 0; i < jobs; i++ {
            newJob := &worker.NewJob{
                Final: ch,
                Do: func() worker.MainJob {
                    return worker.MainJob{ID: i , Message: "test"}
                },
            }
            do.Dispatch(newJob, durationDelay)
        }
        do.Await()
        close(ch)
    }(len(members))

    for v := range ch {
        fmt.Println(v)
    }

when i print the ch
i got this:

{1 test}
{3 test}
{3 test}

so the index of 0 and 2 not called, and where is the index 3 from? the length of members is 3, so it gonna called 0 1 2
do I make mistake here?

the Do in newJob is sent the result of worker.MainJob to Final

it something like this

Final <- Do()

the final is chan worker.MainJob and Do is a function which returns worker.MainJob

Solution

You need to shadow the loop variable.

https://github.com/golang/go/wiki/CommonMistakes#using-reference-to-loop-iterator-variable

        for i := 0; i < jobs; i++ {
            i := i
            newJob := &worker.NewJob{
                Final: ch,
                Do: func() worker.MainJob {
                    return worker.MainJob{ID: i , Message: "test"}
                },
            }
            do.Dispatch(newJob, durationDelay)
        }

Answered By – user14311453

Answer Checked By – Timothy Miller (GoLangFix Admin)

Leave a Reply

Your email address will not be published.