如何在不使用时间的情况下等待所有goroutines完成。睡觉? [英] How to wait for all goroutines to finish without using time.Sleep?

查看:80
本文介绍了如何在不使用时间的情况下等待所有goroutines完成。睡觉?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此代码选择与调用的可执行文件相同的文件夹中的所有xml文件,并对回调方法中的每个结果进行异步处理(在下面的示例中,仅打印文件的名称)。



如何避免使用睡眠方法来避免主要方法退出?我有问题缠绕我的头(我假设这是它需要的,同步结果),所以任何帮助表示赞赏!

 包主要

导入(
fmt
io / ioutil
路径
路径/文件路径
os
runtime
time


func eachFile(扩展字符串,回调函数(文件字符串)){
exeDir:= filepath.Dir(os.Args [0])
文件,_:= ioutil.ReadDir(exeDir)
for _,f:=范围文件{
fileName:= f.Name( )
if extension == path.Ext(fileName){
go callback(fileName)
}
}
}


func main(){
maxProcs:= runtime.NumCPU()
runtime.GOMAXPROCS(maxProcs)

eachFile(。xml,func(fileName string){
//定制逻辑进入这里
fmt.Println(fileName)
})

//这个i我想摆脱
time.Sleep(100 * time.Millisecond)
}


解决方案

您可以使用 sync.WaitGroup

一>。引用链接的例子:

  package main 

import(
net / http
sync


func main(){
var wg sync.WaitGroup
var url = [] string {
http://www.golang.org/,
http://www.google.com/,
http://www.somestupidname.com/,
}
用于_,url:=范围url {
//增加WaitGroup计数器。
wg.Add(1)
//启动一个goroutine来获取URL。
去func(url字符串){
//当goroutine完成时减少计数器。
推迟wg.Done()
//获取URL。
http.Get(url)
(url)
}
//等待所有HTTP抓取完成。
wg.Wait()
}


This code selects all xml files in the same folder, as the invoked executable and asynchronously applies processing to each result in the callback method (in the example below, just the name of the file is printed out).

How do I avoid using the sleep method to keep the main method from exiting? I have problems wrapping my head around channels (I assume that's what it takes, to synchronize the results) so any help is appreciated!

package main

import (
    "fmt"
    "io/ioutil"
    "path"
    "path/filepath"
    "os"
    "runtime"
    "time"
)

func eachFile(extension string, callback func(file string)) {
    exeDir := filepath.Dir(os.Args[0])
    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)
}

解决方案

You can use sync.WaitGroup. Quoting the linked example:

package main

import (
        "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()
}

这篇关于如何在不使用时间的情况下等待所有goroutines完成。睡觉?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆