create multiple goroutines with a function in go

To create multiple goroutines with a function in Go, you need to first define the function that you want to execute concurrently. Then, you can create multiple goroutines by simply calling that function using the go keyword.

Here is an example:

main.go
package main

import (
	"fmt"
	"time"
)

func printNumbers() {
	for i := 1; i <= 5; i++ {
		fmt.Println(i)
		time.Sleep(1 * time.Second)
	}
}

func main() {
	for i := 1; i <= 3; i++ {
		go printNumbers()
	}
	time.Sleep(4 * time.Second)
}
238 chars
21 lines

In this example, the printNumbers function prints numbers from 1 to 5 with a delay of 1 second between each number. The main function creates three goroutines that execute the printNumbers function concurrently using the go keyword.

To ensure that the main function does not exit before the goroutines finish executing, we use the time.Sleep function to pause the execution for four seconds.

When you run this program, you will see that each goroutine executes concurrently and prints the numbers from 1 to 5 in a staggered pattern.

gistlibby LogSnag