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.go238 chars21 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