Goroutines
This Go code demonstrates the basics of goroutines and how they interact with the main program. It illustrates the basics of goroutines, showing how they can run concurrently with the main program and the use of time.Sleep
for synchronization.
Let's break it down with inline comments:
Output
Explanation:
package main
: Indicates that this Go file belongs to the main executable package.import (...)
: Imports necessary packages, including "fmt" for formatting and printing, and "time" for handling time-related operations.func f(from string) { ... }
: Defines a functionf
that takes a string parameterfrom
and prints a message three times with the given prefix.func main() { ... }
: The main function, where the execution of the program begins.f("direct")
: Calls the functionf
in the main goroutine, printing a message directly.go f("goroutine")
: Launches a new goroutine to execute the functionf("goroutine")
concurrently, allowing it to run independently of the main program.go func(msg string) { ... }("going")
: Creates an anonymous function and launches it as a goroutine with a parameter. This demonstrates how to use goroutines with inline function definitions.time.Sleep(time.Second)
: Introduces a delay of one second, giving the goroutines some time to complete before the program exits. This is a simple way to synchronize the main goroutine with the others.fmt.Println("done")
: Prints "done" after the goroutines have had enough time to execute, indicating the end of the program.
Last updated
Was this helpful?