dragon0023 2013-08-13 11:22
浏览 62
已采纳

如何在不使用time.Sleep的情况下等待所有goroutine完成?

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)
}
  • 写回答

5条回答 默认 最新

  • doutuoji8418 2013-08-13 11:25
    关注

    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()
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(4条)

报告相同问题?

悬赏问题

  • ¥15 antv g6 力导向图布局
  • ¥15 各位为什么总是报错attributeerror呢,报nonetype object has no attribute group
  • ¥15 quartz框架,No record found for selection of Trigger with key
  • ¥15 锅炉建模+优化算法,遗传算法优化锅炉燃烧模型,ls-svm会搞,后面的智能算法不会
  • ¥20 MATLAB多目标优化问题求解
  • ¥15 windows2003服务器按你VPN教程设置后,本地win10如何连接?
  • ¥15 求一阶微分方程的幂级数
  • ¥15 关于#线性回归#的问题:【统计】回归系数要转化为相关系数才能进行Fisher' Z转化吗(相关搜索:回归模型)
  • ¥100 使用matlab解决含分段变量的优化问题
  • ¥15 matlab基于鲸鱼算法优化vmd