dongmeng2687 2015-06-18 01:00 采纳率: 0%
浏览 15
已采纳

如何在Go中同步可变数量的频道?

I am testing out concurrency in Go by writing a client (in the form of a web server) that makes many requests to a web server and then returns how long it took to make those requests. Basically a benchmark tool.

Here is to code I am using currently: main.go

I know my code has many flaws but the one I am concerned with at the moment is how much effort it takes test how performance would change if I add more go routine calls. In the CallSync function I have to keep adding on to this massive select statement and to the massive list of calls to the func that starts the go routine. I know there must be a better way. I probably don't even need to synchronize like I am right now, but if I did how could I do this in a more flexible way? I want to have code where I can specify the number of "go routines" to call and it will call that the routine that number of times and synchronize with all the associated channels without having to hard code it all.

  • 写回答

1条回答 默认 最新

  • dptpn06684 2015-06-18 01:50
    关注

    Like @JiangYD suggested, it's easier to just use one channel:

    type resp struct {
        id string
        i  int
    }
    
    func Async(url string, c chan<- resp, id string, count int) {
        cnt := 0
        for i := 0; i < count; i++ {
            GetPage(url)
            cnt = cnt + 1
            if cnt == 50 {
                c <- resp{id, i}
                cnt = 0
            }
        }
    }
    
    func CallSync(w http.ResponseWriter, r *http.Request) {
        t0 := time.Now()
        ch := make(chan resp, 20)
        for i := range [20]struct{}{} {
            go Async("http://localhost:8080/", ch, fmt.Sprintf("ch%02d", i), 2000)
        }
        count := 0
        for count < 4000 {
            select {
            case r := <-ch:
                fmt.Printf("%+v
    ", r)
            default:
            }
        }
        t1 := time.Now()
        diff := t1.Sub(t0)
        num := diff.Nanoseconds() / int64(time.Millisecond)
        msec := float64(num) / 1000
        reqsec := float64(count) / msec
        fmt.Fprintf(w, "%v requests
    ", count)
        fmt.Fprintf(w, "Performed in %v
    ", diff)
        fmt.Fprintf(w, "At a rate of %v (requests/sec)
    ", reqsec)
    }
    

    Another approach is to use reflect.Select but that would just slow things down.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥100 求数学坐标画圆以及直线的算法
  • ¥100 c语言,请帮蒟蒻写一个题的范例作参考
  • ¥15 名为“Product”的列已属于此 DataTable
  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 自己瞎改改,结果现在又运行不了了
  • ¥15 链式存储应该如何解决
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站