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.

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

报告相同问题?

悬赏问题

  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化
  • ¥15 Mirare PLUS 进行密钥认证?(详解)
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥20 想用ollama做一个自己的AI数据库
  • ¥15 关于qualoth编辑及缝合服装领子的问题解决方案探寻
  • ¥15 请问怎么才能复现这样的图呀