Golang Goroutine Link to heading
goroutine 说明 Link to heading
在gobyexample
中对于 Goroutine 的解释是这样 A *goroutine* is a lightweight thread of execution.
中文是"goroutine 是一个轻量级的执行线程".
下面我们来看一段代码比较一下使用 goroutine,和不使用 goroutine 的区别:
package main
import (
"fmt"
"sync"
"time"
)
var wg sync.WaitGroup
func GoRou() {
for i := 0; i < 10; i++ {
wg.Add(1)
go func(i int) {
defer wg.Done()
time.Sleep(1 * time.Second)
fmt.Println("current", i)
}(i)
}
}
func FakeGoRou() {
for i := 0; i < 10; i++ {
wg.Add(1)
func(i int) {
defer wg.Done()
time.Sleep(1 * time.Second)
fmt.Println("current", i)
}(i)
}
}
func main() {
startTime := time.Now()
GoRou()
// FakeGoRou()
wg.Wait()
spendTime := time.Since(startTime)
fmt.Println("Main Done use", spendTime)
}