标签:ocs 一个 字符 code 阻塞 执行 ++ 顺序 syn
WaitGroup它能够一直等到所有的goroutine执行完成,并且阻塞主线程的执行,直到所有的goroutine执行完成。
Add:添加或者减少等待goroutine的数量
Done:相当于Add(-1)
Wait:执行阻塞,直到所有的WaitGroup数量变成0
实例1跟实例2代码区别:少了一行代码go func() {}()
实例1和实例3代码区别:runtime.GOMAXPROCS的入参不一样
package main
import (
"fmt"
"sync"
"runtime"
)
func main() {
N := 26
runtime.GOMAXPROCS(1)
var waitGroup sync.WaitGroup
waitGroup.Add(2*N)
for i := 1; i <= N; i++ {
go func(i int) {
//defer waitGroup.Add(-1)
defer waitGroup.Done()
fmt.Printf("%c ", 96 + i)
}(i)
}
for i := 1; i <= N; i++ {
go func(i int) {
//defer waitGroup.Add(-1)
defer waitGroup.Done()
fmt.Printf("%c ", 64 + i)
}(i)
}
go func() {}()
waitGroup.Wait()
}
运行结果
a b c d e f g h i j k l m n o p q r s t u v w x y z A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
package main
import (
"fmt"
"sync"
"runtime"
)
func main() {
N := 26
runtime.GOMAXPROCS(1)
var waitGroup sync.WaitGroup
waitGroup.Add(2*N)
for i := 1; i <= N; i++ {
go func(i int) {
//defer waitGroup.Add(-1)
defer waitGroup.Done()
fmt.Printf("%c ", 96 + i)
}(i)
}
for i := 1; i <= N; i++ {
go func(i int) {
//defer waitGroup.Add(-1)
defer waitGroup.Done()
fmt.Printf("%c ", 64 + i)
}(i)
}
//go func() {}()
waitGroup.Wait()
}
运行结果
Z a b c d e f g h i j k l m n o p q r s t u v w x y z A B C D E F G H I J K L M N O P Q R S T U V W X Y
package main
import (
"fmt"
"sync"
"runtime"
)
func main() {
N := 26
runtime.GOMAXPROCS(2)
var waitGroup sync.WaitGroup
waitGroup.Add(2*N)
for i := 1; i <= N; i++ {
go func(i int) {
//defer waitGroup.Add(-1)
defer waitGroup.Done()
fmt.Printf("%c ", 96 + i)
}(i)
}
for i := 1; i <= N; i++ {
go func(i int) {
//defer waitGroup.Add(-1)
defer waitGroup.Done()
runtime.Gosched()
fmt.Printf("%c ", 64 + i)
}(i)
}
go func() {}()
waitGroup.Wait()
}
运行结果
c a b q d e f g h i j k r l m s n t o u p v w x K y z L M T N U O P V Q W R X S Y C Z D A B H E I F J G
标签:ocs 一个 字符 code 阻塞 执行 ++ 顺序 syn
原文地址:http://blog.51cto.com/12880687/2129462