该代码选择同一文件夹中的所有xml文件,作为被调用的可执行文件,并以异步方式将处理应用于回调方法中的每个结果(在下面的示例中,仅打印文件名)。
如何避免使用sleep方法阻止main方法退出?我在解决问题时遇到了麻烦(我想这就是同步结果所必需的),因此,我们将不胜感激!
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) }
您可以使用sync.WaitGroup。引用链接的示例:
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() }