In Go, creating goroutines is straightforward and intuitive. Goroutines are Go's lightweight threads designed for executing parallel tasks. The fundamental method to create a goroutine is to prepend the go keyword before the function call. This allows the function to run asynchronously in a new goroutine. Let's explore this with an example to illustrate how to create and use goroutines.
Assume we have a simple function that prints numbers from 1 to 5, pausing for one second after printing each number:
gopackage main import ( "fmt" "time" ) func printNumbers() { for i := 1; i <= 5; i++ { fmt.Println(i) time.Sleep(time.Second) } }
If we directly call printNumbers(), it executes synchronously, meaning the main program waits for this function to complete before proceeding to the next line of code. To run this function in the background without blocking other operations of the main program, we can use the go keyword when calling the function, as shown below:
gopackage main import ( "fmt" "time" ) func main() { go printNumbers() // The main program continues with other operations fmt.Println("Starting other tasks") time.Sleep(6 * time.Second) // Ensuring the main goroutine does not exit prematurely fmt.Println("Main program ends") }
In this example, we start a goroutine within the main function to execute printNumbers. Because the go keyword is used, printNumbers runs asynchronously in a new goroutine, meaning the main function proceeds immediately to the next line of code after launching the goroutine, without waiting for printNumbers to complete.
The output will resemble:
shellStarting other tasks 1 2 3 4 5 Main program ends
As observed, the printing of numbers and 'Starting other tasks' occur almost simultaneously, indicating that printNumbers executes in a separate goroutine in parallel.
Through this example, we can see that creating goroutines in Go is straightforward—simply prefix the function call with the go keyword. This makes concurrent programming in Go both easy and intuitive.