Skip to content
Go

goroutine

Implement concurrency using goroutines.

By EZ4Code Team
goroutineconcurrency

Code

package main

import (
    "fmt"
    "sync"
    "time"
)

func main() {
    var wg sync.WaitGroup
    for i := 0; i < 5; i++ {
        wg.Add(1)
        go func(n int) {
            defer wg.Done()
            time.Sleep(time.Second)
            fmt.Println("goroutine", n)
        }(i)
    }
    wg.Wait()
    fmt.Println("done")
}

Explanation

The go keyword starts a goroutine; WaitGroup waits for all goroutines to finish.

More Go Snippets