Saturday, October 1, 2022

[FIXED] Why can't this program print anything using goroutine?

Issue

I'm recently looking into Golang by google and I met with the following problem. Then program doesn't print anything. But if I remove the "go" notations, it will print both "goroutine" and "going".

package main

import "fmt"

func f(msg string) {
    fmt.Println(msg)
    return
}

func main() {
    go f("goroutine")

    go func(msg string) {
        fmt.Println(msg)
        return
    }("going")

    return
}

Solution

Your code needs to wait for the routines to finish before exiting. A good way to do this is to pass in a channel which is used by the routine to signal when it's done and then wait in the main code. See below.

Another advantage of this approach is that it allows/encourages you to perform proper error handling based on the return value.

package main

import (
    "fmt"
)

func f(msg string, quit chan int) {
    fmt.Println(msg)
    quit <- 0
    return
}

func main() {

    ch1 := make(chan int)
    ch2 := make(chan int)

    go f("goroutine", ch1)

    go func(msg string, quit chan int) {
        fmt.Println(msg)
        quit <- 0
        return
    }("going", ch2)

    <-ch1
    <-ch2
    return
}


Answered By - Usman Ismail
Answer Checked By - David Goodson (PHPFixing Volunteer)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.