create a goroutine in go

In Go, a goroutine is a lightweight thread that allows a function to be executed concurrently with other functions. Goroutines are the building blocks of concurrent and parallel programming in Go.

Creating a goroutine is simple. You can use the go keyword followed by a function call to create and run a new goroutine.

Here's an example:

main.go
package main

import (
    "fmt"
    "time"
)

func main() {
    go printNumbers()
    go printLetters()
    time.Sleep(1 * time.Second)
}

func printNumbers() {
    for i := 1; i <= 5; i++ {
        fmt.Printf("%d ", i)
        time.Sleep(100 * time.Millisecond)
    }
}

func printLetters() {
    for i := 'a'; i <= 'e'; i++ {
        fmt.Printf("%c ", i)
        time.Sleep(100 * time.Millisecond)
    }
}
409 chars
27 lines

In this example, we defined two functions printNumbers and printLetters, each printing a sequence of numbers and letters respectively with some delay using the time.Sleep function to simulate some work being done.

In the main function, we create two goroutines that execute these functions by using the go keyword followed by a function call. We also call time.Sleep to give the program enough time to run the goroutines.

When we run this program, we get the output:

main.go
1 a 2 3 b 4 c 5 d e
20 chars
2 lines

Note that the printNumbers and printLetters functions are executed concurrently, with their output interleaved. This is because the two goroutines are executing simultaneously and independently, using the CPU cores available to run in parallel.

Concurrency in Go is achieved through goroutines, and communication between goroutines is achieved through channels. Together, they make it easy to write concurrent and parallel programs in an efficient and safe way.

gistlibby LogSnag