并发打印
●错误代码
这个代码不会打印任何东西,因为main没等到pnt返回就直接返回了
package main
import (
"fmt"
"time"
)
func pnt() {
time.Sleep(2 * time.Second)
fmt.Println("hello world!!!")
}
func main() {
for i := 0; i < 5; i++ {
go pnt()
}
}
●正确代码
让5个goroutine向共享的channel中发送事件,main中接收到5个ch才会返回
package main
import (
"fmt"
"time"
)
func pnt() {
time.Sleep(2 * time.Second)
fmt.Println("hello world!!!")
}
func main() {
ch := make(chan struct{
})