多 goroutine 问题

2016-03-14 12:33:08 +08:00
 seacoastboy
package main
import (
        "fmt"
)

func main(){
        var str = []string {"1", "2", "1","1", "2","1", "2", "1","1", "2","1", "2", "1","1", "2","1", "2", "1","1", "2", "0", "6","9","4"}
        for _, t := range str {
                switch t {
                case "1":
                        go go1(t)
                case "2":
                        go go2(t)
                default:
                        //
                }
        }

        fmt.Println("hello")


}


func go1(st string) {
        //逻辑处理
        fmt.Println(st)
}
func go2(st string){
        //逻辑处理
        fmt.Println(st)
}

我开启 2 个 goroutine , 但是我不知道如何做堵塞,确保 2 个 goroutine 都运行完后在退出主 goroutine 。开始的时候我用 channel 加 计数器去实现,这样的话就需要给函数添加一个参数:

func go1(st string, ch chan bool){
    //逻辑处理
}
func go2(st string, ch chan bool){
    //逻辑处理
}
func main(){
    //省略一些代码
    for {
        <- ch
        t ++
        if t >= len(str) {
            break
        }
    }
}

我想问问, 能不能有更简介明了的办法去实现。

692 次点击
所在节点    Go 编程语言
7 条回复
mkeith
2016-03-14 13:03:03 +08:00
go 语言 WaitGroup 用法
http://www.baiyuxiong.com/?p=913
darasion
2016-03-14 13:03:47 +08:00
sync 包有个 WaitGroup 可以满足你的需要。
zts1993
2016-03-14 13:13:37 +08:00
看上去你这个好像不止会产生两个 goroutine 哦。。。
seacoastboy
2016-03-14 15:43:55 +08:00
@darasion 对的使用 WaitGroup 可以实现。
@zts1993 有 for 产生很多多 goroutine 的,

我想使用一个全局的 channel 来实现。
darasion
2016-03-24 18:28:16 +08:00
@seacoastboy https://golang.org/doc%2Fcodewalk%2Furlpoll.go
这里貌似有个 Poller 函数,是不是你想要的?
想停下 goroutine 的话,发送端 close 就好。
cobopanda
2016-04-27 16:16:42 +08:00
看看 WaitGroup 的用法
cobopanda
2016-04-27 17:13:23 +08:00
以下代码仅供参考
package main

import (
"fmt"
"runtime"
)

func main() {
data := []int{1, 8, 6, 7, 20}
NumCPU := runtime.NumCPU()
fmt.Println("NumCPU:", NumCPU)
sem := make(chan int, NumCPU)
for _, value := range data {
if value%2 == 0 {
go func(param int) {
sem <- param
fmt.Println("oushu:", param)
}(value)
} else {
go func(param int) {
sem <- param
fmt.Println("jishu:", param)
}(value)
}
}

for i := 0; i < len(data); i++ {
<-sem
}
}

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/263340

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX