Go-routines with channels not running parallely

Issue

package main
import "time"
func main() {
    stringCh := make(chan func() (string))
    go func() {
        stringCh <- func() (string) {
            return stringReturner()
        }
        close(stringCh)
    }()

    intCh := make(chan func() (int))
    go func() {
        intCh <- func() (int) {
            return intReturner()
        }
        close(intCh)
    }()

    str := (<-stringCh)()
    print("Printing str: ", str,"\n\n")
    num := (<-intCh)()
    print("Printing int: ", num,"\n\n")     
}

func intReturner()int{
    time.Sleep(5 * time.Second)
    print("Inside int returner\n\n");
    return 1;
}

func stringReturner()string{
    time.Sleep(5 * time.Second)
    print("Inside string returner\n\n");
    return "abcd";
}

Output:

Inside string returner

Printing str: abcd

WAIT OF 5 SECONDS

Inside int returner

Printing int: 1

https://play.golang.org/p/oE2ybs7Jo-W

Why is this coding taking 10 seconds to execute instead of 5? We are parallelizing the calls by spawning two go-routines right (1 for string returner and 1 for int returner), but why is the int returner executing after the string returner executes?

Solution

The channel is returning function with sleep, and such function got called in sequential manner. That is why it will take 10s in general.

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

Answered By – sayboras

Answer Checked By – Robin (GoLangFix Admin)

Leave a Reply

Your email address will not be published.