并发
1.通过go关键字创建并发任务
package main
func main(){
go println("hello word")
}
package main
func main(){
go println("hello word")
go func (s string){
println(s)
}("hello word")
}
2.与defer一样,goroutine也会因延迟执行而立即计算并复制执行参数。
package main
import "time"
var c int
func counter() int {
c++
return c
}
func main(){
a:= 100
go func(x, y int){
time.Sleep(time.Second)
println("go:",x,y)
}(a, counter())
a+=100
println("main:" , a, counter())
time.Sleep(time.Second*3)
}
结果
main: 200 2
go: 100 1
3.wait 进程退出时不会等待并发任务结束,可用通道channel进行阻塞,最后发出退出信号
package main
import (
"time"
)
func main() {
exit := make(chan struct{})
go func() {
time.Sleep(time.Second)
println("goroutine done.")
close(exit)
}()
println("main...")
<-exit
println("main exit")
}
4.sync.WaitGroup的使用
package main
import (
"sync"
"time"
)
func main() {
var wg sync.WaitGroup
for i:=0;i<10;i++{
wg.Add(1)
go func(id int) {
defer wg.Done()
time.Sleep(time.Second)
println("goroutine", id, "done.")
}(i)
}
println("main...")
wg.Wait()
println("main exit")
}