golang中如何监控多个goroute协程是否执行完成
发布时间:2020-12-16 09:21:30 所属栏目:大数据 来源:网络整理
导读:golang中如何监控多个goroute协程是否执行完成 package mainimport ( "fmt")// 将intchan管道中的素数插入到管道resultchan中,协程完成关闭时在exitchan中记录一次func calc(intchan,resultchan,exitchan chan int) { for v := range intchan { flag := tru
golang中如何监控多个goroute协程是否执行完成package main import ( "fmt" ) // 将intchan管道中的素数插入到管道resultchan中,协程完成关闭时在exitchan中记录一次 func calc(intchan,resultchan,exitchan chan int) { for v := range intchan { flag := true for i := 2; i < v && flag == true; i++ { if v%i == 0 { flag = false break } } if flag { fmt.Println(v,"is 素数") resultchan <- v } } exitchan <- 1 // 记录协程管斌 } func main() { var ( IntChan = make(chan int,1000) ResultChan = make(chan int,1000) ExitChan = make(chan int,8) ) for i := 0; i < 100; i++ { IntChan <- i } close(IntChan) for i := 0; i < 8; i++ { // 总共开了8个goroute go calc(IntChan,ResultChan,ExitChan) } go func() { for i := 0; i < 8; i++ { // 从exitchan管道中获取到8次goroute完成完毕记录才放行 a := <-ExitChan // 没有记录的话会堵塞,会等下次的记录被插入才会放行 } close(ResultChan) // 8此循环结束代表8个收集素数的goroute全部完成完毕了,此时才能关闭resultchan,为的是让下面for循环取完resultchan管道中值的时可以正常退出 }() for v := range ResultChan { fmt.Println(v) } } // 0-100的所有素数 0 1 2 5 7 11 13 17 3 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |