golang goroutine code example
Example 1: 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()
}
Example 2: goroutine
// just a function (which can be later started as a goroutine)
func doStuff(s string) {
}
func main() {
// using a named function in a goroutine
go doStuff("foobar")
// using an anonymous inner function in a goroutine
go func (x int) {
// function body goes here
}(42)
}
Example 3: run thread golang
func f(s string){
fmt.Println(s)
}
func main(){
go f("goroutine")
}
Example 4: goroutine
package main