##### 为什么每次都能够执行成功?(go版本1.11,GOMAXPROCS 默认为CPU最大核数,即代码并行执行)
```golang
package main
import (
"fmt"
"time"
)
func main() {
arra := []int64{1,2,3,4}
arrb := []string{"a","b","c","d"}
c := make(chan bool)
go func(arra []int64) {
for i:=0;i < len(arra);i++ {
if flag := <-c;flag{
fmt.Println(arra[i])
c <- false
}
}
}(arra)
go func(arrb []string) {
for i:=0;i < len(arrb);i++ {
if flag := <- c;!flag{
fmt.Println(arrb[i])
c <- true
}
}
}(arrb)
c <- false
time.Sleep(time.Second * 2)
}
```
通过测试,下面执行的概率远远大于上面协程的执行概率。
```go
package main
import (
"testing"
"fmt"
)
func GoTest() bool {
c := make(chan bool)
content := make(chan bool)
go func() {
<-c
content <- false
}()
go func() {
<-c
content <- true
}()
c <- true
return <-content
}
func TestChannel(t *testing.T) {
result := map[bool]float64{true:0,false:0}
for i :=0; i <= 10000; i++ {
if GoTest() {
result[true] ++
}else {
result[false]++
}
}
fmt.Println(result)
fmt.Printf("true概率:%f%s\n",result[true]/10000 *100,"%")
fmt.Printf("false概率:%f%s\n",result[false]/10000 * 100,"%")
}
```
result
```
map[true:9200 false:801]
true概率:92.000000%
false概率:8.010000%
```
#7
更多评论
##### 代码并行执行时,执行顺序不定,以下代码输出无规律
```go
package main
import (
"fmt"
"time"
)
func main() {
go func() {
fmt.Println(1)
}()
go func() {
fmt.Println(2)
}()
go func() {
fmt.Println(3)
}()
time.Sleep(time.Second * 1)
}
```
#1