Goroutines in action

Now that we have a basic understanding of the underlying principles of goroutines, we can check them out in action. In the following code block, we will see how to invoke a goroutine using the go call:

package main

import (
"fmt"
"time"
)

func printSleep(s string) {
for index, stringVal := range s {
fmt.Printf("%#U at index %d ", stringVal, index)
time.Sleep(1 * time.Millisecond) // printSleep sleep timer
}
}

func main() {
const t time.Duration = 9
go printSleep("HELLO GOPHERS")
time.Sleep(t * time.Millisecond) // Main sleep timer
fmt.Println("sleep complete")
}

During the execution of this function, we only get a partial return of the printSleep() function wrapped in the goroutine call (printing HELLO GOPHERS) before the main sleep timer is complete. Why did this happen? If the main() goroutine completes, it is closed, the program is terminated, and leftover goroutines will not run. We were able to get the first nine characters returned because those goroutines completed before the main function finished executing. If we change our const t duration to 14, we will receive the entire HELLO GOPHERS string.  The reason behind this is that the main function does not get completed before all of the goroutines that spawned around go printSleep() are executed.  Goroutines are powerful only if used correctly.

Another Go built-in that helps with managing concurrent goroutines is Go channels, which is the topic we will cover in the next section.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.143.4.181