停止嵌套循环执行并继续外层循环
来源:stackoverflow
时间:2024-02-10 19:06:15 341浏览 收藏
目前golang学习网上已经有很多关于Golang的文章了,自己在初次阅读这些文章中,也见识到了很多学习思路;那么本文《停止嵌套循环执行并继续外层循环》,也希望能帮助到大家,如果阅读完后真的对你学习Golang有帮助,欢迎动动手指,评论留言并分享~
问题内容
我弄清楚如何每次使用不同代理进行“多线程”请求的最佳方法是将 go func 和 for 循环嵌套在另一个 for 循环中,但我不知道如何停止所有循环就像通常的中断一样,我尝试了常规中断,也尝试了中断并添加了:在循环上方,但这并没有阻止它。
package main import ( "log" "encoding/json" "github.com/parnurzeal/gorequest" ) func main(){ rep := 100 for i := 0; i < rep; i++ { log.Println("starting loop") go func() { for{ request := gorequest.New() resp, body, errs := request.Get("https://discord.com/api/v9/invites/family").End() if errs != nil { return } if resp.StatusCode == 200{ var result map[string]interface{} json.Unmarshal([]byte(body), &result) serverName := result["guild"].(map[string]interface{})["name"] log.Println(sererName +" response 200, closing all loops") //break all loops and goroutine here } } } } log.Println("response 200,closed all loops")
正确答案
使用 parnurzeal/gorequest
会使回答这个问题变得复杂,因为该包没有提供任何明显的方法来取消请求(请参阅 this issue)。因为您的重点似乎是过程而不是特定的函数,所以我刚刚使用了标准库(http
)(如果您确实需要使用 gorequest
那么也许专门询问一个与此相关的问题)。
无论如何,下面的解决方案演示了一些事情:
- 使用 Waitgroup,以便它知道所有 go 例程何时完成(这里不是必需的,但通常您想知道您已完全关闭)
- 通过通道传递结果(从 goroutine 更新共享变量会导致 data races)。
- 使用 context 进行取消。当我们得到结果时,将调用
cancel
函数,这将停止正在进行的请求。
package main import ( "context" "encoding/json" "errors" "fmt" "log" "net/http" "sync" ) func main() { // Get the context and a function to cancel it ctx, cancel := context.WithCancel(context.Background()) defer cancel() // Not really required here but its good practice to ensure context is cancelled eventually. results := make(chan string) const goRoutineCount = 100 var wg sync.WaitGroup wg.Add(goRoutineCount) // we will be waiting on 100 goRoutines for i := 0; i < goRoutineCount; i++ { go func() { defer wg.Done() // Decrement WaitGroup when goRoutine exits req, err := http.NewRequestWithContext(ctx, http.MethodGet, "https://discord.com/api/v9/invites/family", nil) if err != nil { panic(err) } resp, err := http.DefaultClient.Do(req) if err != nil { if errors.Is(err, context.Canceled) { return // The error is due to the context being cancelled so just shutdown } panic(err) } defer resp.Body.Close() // Ensure body is closed if resp.StatusCode == 200 { var result map[string]interface{} if err = json.NewDecoder(resp.Body).Decode(&result); err != nil { panic(err) } serverName := result["guild"].(map[string]interface{})["name"] results <- serverName.(string) // Should error check this... cancel() // We have a result so all goroutines can stop now! } }() } // We need to process results until everything has shutdown; simple approach is to just close the channel when done go func() { wg.Wait() close(results) }() var firstResult string requestsProcessed := 0 for x := range results { fmt.Println("got result") if requestsProcessed == 0 { firstResult = x } requestsProcessed++ // Possible that we will get more than one result (remember that requests are running in parallel) } // At this point all goroutines have shutdown if requestsProcessed == 0 { log.Println("No results received") } else { log.Printf("xx%s response 200, closing all loops (requests processed: %d)", firstResult, requestsProcessed) } }
以上就是《停止嵌套循环执行并继续外层循环》的详细内容,更多关于的资料请关注golang学习网公众号!
声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
-
502 收藏
-
502 收藏
-
501 收藏
-
501 收藏
-
501 收藏
最新阅读
更多>
-
139 收藏
-
204 收藏
-
325 收藏
-
477 收藏
-
486 收藏
-
439 收藏
-
357 收藏
-
352 收藏
-
101 收藏
-
440 收藏
-
212 收藏
-
143 收藏
课程推荐
更多>
-
- 前端进阶之JavaScript设计模式
- 设计模式是开发人员在软件开发过程中面临一般问题时的解决方案,代表了最佳的实践。本课程的主打内容包括JS常见设计模式以及具体应用场景,打造一站式知识长龙服务,适合有JS基础的同学学习。
- 立即学习 542次学习
-
- GO语言核心编程课程
- 本课程采用真实案例,全面具体可落地,从理论到实践,一步一步将GO核心编程技术、编程思想、底层实现融会贯通,使学习者贴近时代脉搏,做IT互联网时代的弄潮儿。
- 立即学习 508次学习
-
- 简单聊聊mysql8与网络通信
- 如有问题加微信:Le-studyg;在课程中,我们将首先介绍MySQL8的新特性,包括性能优化、安全增强、新数据类型等,帮助学生快速熟悉MySQL8的最新功能。接着,我们将深入解析MySQL的网络通信机制,包括协议、连接管理、数据传输等,让
- 立即学习 497次学习
-
- JavaScript正则表达式基础与实战
- 在任何一门编程语言中,正则表达式,都是一项重要的知识,它提供了高效的字符串匹配与捕获机制,可以极大的简化程序设计。
- 立即学习 487次学习
-
- 从零制作响应式网站—Grid布局
- 本系列教程将展示从零制作一个假想的网络科技公司官网,分为导航,轮播,关于我们,成功案例,服务流程,团队介绍,数据部分,公司动态,底部信息等内容区块。网站整体采用CSSGrid布局,支持响应式,有流畅过渡和展现动画。
- 立即学习 484次学习