goroutines golang example

Example: golang goroutines

package main

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

func waitGroup() {
	var wg sync.WaitGroup

	wg.Add(1)
	go func() {
		defer wg.Done()
		fmt.Println("hello world 1")
	}()

	wg.Add(1)
	go func() {
		defer wg.Done()
		fmt.Println("hello world 2")
	}()

	wg.Add(1)
	go func() {
		defer wg.Done()
		fmt.Println("hello world 3")
	}()

	wg.Wait()
}

func sleepTime() {
	go func() {
		fmt.Println("hello world 4")
	}()

	go func() {
		fmt.Println("hello world 5")
	}()

	go func() {
		fmt.Println("hello world 6")
	}()

	time.Sleep(time.Second * 1)
}

func main() {
	// waitGroup()
	sleepTime()
}

Tags:

Go Example