gpt4 book ai didi

go - Go 中的并发

转载 作者:IT王子 更新时间:2023-10-29 02:01:09 25 4
gpt4 key购买 nike

如何在 Go 中实现聚合模式,我必须同时发送一堆 http 请求,每个 go 例程将调用端点并在 channel 上发送响应状态。现在在主调用函数上,我将通过 channel 进行范围并显示所有响应。

问题是如何解锁 channel ?? - 我无法从 go 例程中关闭 channel ,因为它会在完成全部工作之前关闭

主要包

import (
"fmt"
"net/http"
"sync"
"time"

"golang.org/x/net/context"
)

func main() {

var wg sync.WaitGroup
wg.Add(10)
c := make(chan string, 100)
ctx := context.Background()

ctx, cancel := context.WithTimeout(ctx, 5*time.Second)

defer cancel()
for i := 1; i <= 10; i++ {
go SendHttpRequest(ctx, c, &wg)
}

for v := range c {
fmt.Println(v)
}

wg.Wait()

}

func SendHttpRequest(ctx context.Context, c chan string, wg *sync.WaitGroup) {

//defer wg.Done()
client := http.Client{}
req, err := http.NewRequest("POST", "https://jsonplaceholder.typicode.com/posts/1", nil)
if err != nil {
panic(err)
}
req.WithContext(ctx)

res, _ := client.Do(req)

select {
case <-time.After(1 * time.Microsecond):
c <- res.Status
case <-ctx.Done():
c <- "599 ToLong"
}
if res != nil {
defer res.Body.Close()
}
//close(c)
defer wg.Done()
}

最佳答案

使用 WaitGroup

go func(){
wg.Wait()
close(c)
}()

for v := range c {
fmt.Println(v)
}

// Don't bother with wg.Wait() here

关于go - Go 中的并发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53676481/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com