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条)

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度