Go 语言并发
启动单个goroutine
package main
import (
"fmt"
"time"
)
func hello(){
fmt.Println("hello")
}
func main() {
go hello()
fmt.Println("欢迎来到编程狮")
time.Sleep(time.Second)
}
sync.WaitGroup
package main
import (
"fmt"
"sync"
)
var wg sync.WaitGroup
func hello() {
fmt.Println("hello")
defer wg.Done()//把计算器-1
}
func main() {
wg.Add(1)//把计数器+1
go hello()
fmt.Println("欢迎来到编程狮")
wg.Wait()//阻塞代码的运行,直到计算器为0
}
启动多个goroutine
package main
import (
"fmt"
"sync"
)
var wg sync.WaitGroup
func hello(i int) {
fmt.Printf("hello,欢迎来到编程狮%v\n", i)
defer wg.Done()//goroutine结束计数器-1
}
func main() {
for i := 0; i < 10; i++ {
go hello(i)
wg.Add(1)//启动一个goroutine计数器+1
}
wg.Wait()//等待所有的goroutine执行结束
}