# 使用 Gorutine

``````package main

import (
"fmt"
"math/rand"
"time"
)

func random(min, max int) int {
rand.Seed(time.Now().Unix())
return rand.Intn(max-min) + min
}

func main() {
flags := [...]bool{true, false}
totalStep := 10
tortoiseStep := 0
hareStep := 0
fmt.Println("龜兔賽跑開始...")
for tortoiseStep < totalStep && hareStep < totalStep {
tortoiseStep++
fmt.Printf("烏龜跑了 %d 步...\n", tortoiseStep)
isHareSleep := flags[random(1, 10)%2]
if isHareSleep {
fmt.Println("兔子睡著了zzzz")
} else {
hareStep += 2
fmt.Printf("兔子跑了 %d 步...\n", hareStep)
}
}
}
``````

``````package main

import (
"fmt"
"math/rand"
"time"
)

func random(min, max int) int {
rand.Seed(time.Now().Unix())
return rand.Intn(max-min) + min
}

func tortoise(totalStep int) {
for step := 1; step <= totalStep; step++ {
fmt.Printf("烏龜跑了 %d 步...\n", step)
}
}

func hare(totalStep int) {
flags := [...]bool{true, false}
step := 0
for step < totalStep {
isHareSleep := flags[random(1, 10)%2]
if isHareSleep {
fmt.Println("兔子睡著了zzzz")
} else {
step += 2
fmt.Printf("兔子跑了 %d 步...\n", step)
}
}
}

func main() {
totalStep := 10

go tortoise(totalStep)
go hare(totalStep)

time.Sleep(5 * time.Second) // 給予時間等待 Goroutine 完成
}
``````

# 使用 sync.WaitGroup

`sync.WaitGroup` 可以用來等待一組 Goroutine 的完成，主流程中建立 `sync.WaitGroup`，並透過 `Add` 告知要等待的 Goroutine 數量，並使用 `Wait` 等待 Goroutine 結束，而每個 Goroutine 結束前，必須執行 `sync.WaitGroup``Done` 方法。

``````package main

import (
"fmt"
"math/rand"
"sync"
"time"
)

func random(min, max int) int {
rand.Seed(time.Now().Unix())
return rand.Intn(max-min) + min
}

func tortoise(totalStep int, wg *sync.WaitGroup) {
defer wg.Done()

for step := 1; step <= totalStep; step++ {
fmt.Printf("烏龜跑了 %d 步...\n", step)
}
}

func hare(totalStep int, wg *sync.WaitGroup) {
defer wg.Done()

flags := [...]bool{true, false}
step := 0
for step < totalStep {
isHareSleep := flags[random(1, 10)%2]
if isHareSleep {
fmt.Println("兔子睡著了zzzz")
} else {
step += 2
fmt.Printf("兔子跑了 %d 步...\n", step)
}
}
}

func main() {
wg := new(sync.WaitGroup)

totalStep := 10

go tortoise(totalStep, wg)
go hare(totalStep, wg)

wg.Wait()
}
``````

``````runtime.GOMAXPROCS(runtime.NumCPU())
``````