如何在不使用 time.Sleep 的情况下等待所有 goroutines 完成?
技术问答
257 人阅读
|
0 人回复
|
2023-09-12
|
代码选择同一文件夹中的所有 xml 文件作为调用的可执行文件,并异步处理应用于回调方法的每个结果(文件名称仅在以下示例中打印)。( g6 \: _5 t- @' o+ l; r5 }
如何避免使用 sleep 防止 main 退出方法?我在处理频道时遇到了问题(我认为这是同步结果所需要的),所以谢谢你的帮助!* l/ `5 I3 e. ] { Y
package mainimport "fmt" "io/ioutil" "path" "path/filepath" "os" "runtime" "time")func eachFile(extension string,callback func(file string)) exeDir := filepath.Dir(os.Args files,_ := ioutil.ReadDir(exeDir) for _,f := range files fileName := f.Name() if extension == path.Ext(fileName) go callback(fileName) func main() maxProcs := runtime.NumCPU() runtime.GOMAXPROCS(maxProcs) eachFile(".xml",func(fileName string) { // Custom logic goes in here fmt.Println(fileName) }) // This is what i want to get rid of time.Sleep(100 * time.Millisecond)}# l X9 V7 i( O8 v/ q7 J8 |
% o Z% g% t, l# s: z9 n- D( X 解决方案:
0 k/ I9 [9 M3 s0 a 您可以使用sync.WaitGroup。引用链接的例子:
# a6 y1 V' r$ e; b/ p X1 ?" Xpackage mainimport ( "net/http" "sync")func main()(){ var wg sync.WaitGroup var urls = []string "http://www.golang.org/", "http://www.google.com/", "http://www.somestupidname.com/", for _,url := range urls // Increment the WaitGroup counter. wg.Add(1) Launch a goroutine to fetch the URL. go func(url string) // Decrement the counter when the goroutine completes. defer wg.Done() Fetch the URL. http.Get(url) (url) // Wait for all HTTP fetches to complete. wg.Wait()}
' S0 K3 A, }. R( s5 Q* r |
|
|
|
|
|