I have the following code:
package main import "net" import "fmt" import "bufio" func main() { conn, _ := net.Dial("tcp", "irc.freenode.net:6667") reader := bufio.NewReader(conn) go func() { str, err := reader.ReadString('\n') if err != nil { // handle it fmt.Println(err) } fmt.Println(str) }() }
If I don't have the code that reads from the buffer in a goroutine, it outputs a message like this, which is what I expect to happen:
:zelazny.freenode.net NOTICE * :*** Looking up your hostname...
However, having it inside a goroutine prints nothing.
Can someone explain why that is?
In this case, the main GoRoutine will not wait for another GoRoutine to complete and it will execute the line fmt. Println("hello from main") immediately and exit before the print() function can print its message.
The common methods (fmt. printLine) are not safe.
The fmt. Println() function in Go language formats using the default formats for its operands and writes to standard output. Here spaces are always added between operands and a newline is appended at the end. Moreover, this function is defined under the fmt package.
The WaitGroup type of sync package, is used to wait for the program to finish all goroutines launched from the main function. It uses a counter that specifies the number of goroutines, and Wait blocks the execution of the program until the WaitGroup counter is zero.
In the main function you can use waitGroup.Wait () and this will wait until waitGroup.Done () has been called for each added goroutine. Write data to a channel ch at the end of goroutine and read data from ch out of goroutine can make the main function waiting for goroutine print message.
After the call to go hello () in line no. 11, the control returned immediately to the next line of code without waiting for the hello goroutine to finish and printed main function. Then the main Goroutine terminated since there is no other code to execute and hence the hello Goroutine did not get a chance to run. Let's fix this now.
The main Goroutine should be running for any other Goroutines to run. If the main Goroutine terminates then the program will be terminated and no other Goroutine will run. I guess now you will be able to understand why our Goroutine did not run.
In Go language, fmt package implements formatted I/O with functions analogous to C’s printf () and scanf () function. The fmt.Println () function in Go language formats using the default formats for its operands and writes to standard output.
Your program will exit when the main()
function finishes. This is likely to happen before your goroutine has time to run and print its output.
One option would be to have the main goroutine block reading from a channel, and have the goroutine write to the channel when it has completed its work.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With