使用sync
package main
import (
“fmt”
“runtime”
“sync”
)
func main() {
runtime.GOMAXPROCS(runtime.NumCPU())
fmt.Println(runtime.NumCPU())
wg := sync.WaitGroup{}
wg.Add(10)
for i := 0; i < 10; i++ {
go Go(&wg, i)
}
wg.Wait()
}
func Go(wg *sync.WaitGroup, index int) {
a := 1
for i := 0; i < 100000000; i++ {
a += 1
}
fmt.Println(index, a)
wg.Done()
}
[/go]
使用chan
package main
import (
“fmt”
“runtime”
)
func main() {
runtime.GOMAXPROCS(runtime.NumCPU())
fmt.Println(runtime.NumCPU())
c := make(chan bool, 10)
for i := 0; i < 10; i++ {
go Go(c, i)
}
for i := 0; i < 10; i++ {
<-c
}
}
func Go(c chan bool, index int) {
a := 1
for i := 0; i < 100000000; i++ {
a += 1
}
fmt.Println(index, a)
c <- true
}
[/go]
go chan解释
package main
import (
“fmt”
“time”
)
func main() {
c := make(chan bool)
go func() {
time.Sleep(1 * time.Second)
fmt.Println(“Please go!”)
<-c
time.Sleep(1 * time.Second)
}()
c <- true
}
/*
chan c是缓存的情况的,那么它就是同步阻塞的
如果chan c是有缓存的,那么它就是异步非阻塞的,
异步非阻塞的情况,这里是不会输出信息的,
无缓冲的情况,需要将所有信息读取出来才会结束程序
*/
[/go]