PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Saturday, October 1, 2022

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

 October 01, 2022     concurrency, go     No comments   

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)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home
View mobile version

0 Comments:

Post a Comment

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

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing