go语言怎样开多进程图文讲解。
今天给大家讲解下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
}
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。