今天给大家讲解下go语言开多进程。
package main
import (
"fmt"
"time"
)
var c chan int
func main() {
c = make(chan int)
go waiting("coffee", 1)
go waiting("tea", 2)
fmt.Println("I,am waiting")
//time.Sleep(3 * time.Second)
<-c
<-c
}
func waiting(w string, sec int) {
time.Sleep(time.Duration(sec) * time.Second)
fmt.Println(w, "is ready")
c <- 1
}
如果进程开的比较多,怎样去避免去写多个结束进程的channel,下面我来给大家发下改进版:
package main
import (
"fmt"
"time"
)
var c chan int
func main() {
c = make(chan int)
go waiting("coffee", 1)
go waiting("tea1", 2)
go waiting("tea2", 3)
go waiting("tea3", 4)
go waiting("tea4", 5)
go waiting("tea5", 6)
go waiting("tea6", 7)
fmt.Println("I,am waiting")
//time.Sleep(3 * time.Second)
i := 0
L:
for {
select {
case <-c:
i++
if i > 6 {
break L
}
}
}
}
func waiting(w string, sec int) {
time.Sleep(time.Duration(sec) * time.Second)
fmt.Println(w, "is ready")
c <- 1
}
有疑问加站长微信联系(非本文作者)