golang 实现并发计算文件数量
package main import ( "fmt" "io/ioutil" "os" ) func listDir(path string, ch chan int) { fmt.Println("waiting ..... read path:" + path) files, _ := ioutil.ReadDir(path) FileSlice := []string{} DirSlice := []string{} for _, fi := range files { if fi.IsDir() { //listDir(path + "/" + fi.Name()) DirSlice = append(DirSlice, path+"/"+fi.Name()) //fmt.Println("dir:" + path + "/" + fi.Name()) } else { FileSlice = append(FileSlice, path+"/"+fi.Name()) } } //return slice var count int count = 0 //var FindFiles string for _, value := range FileSlice { fmt.Println("file:" + value) //FindFiles += value + ";" count++ } //find sub directory by go pattern DirCount := len(DirSlice) fmt.Println("dir len:", DirCount) if DirCount > 0 { DirCH := make([]chan int, DirCount) i := 0 for _, value := range DirSlice { fmt.Println("dir:" + value) DirCH[i] = make(chan int) go listDir(value, DirCH[i]) i++ } fmt.Println("wait routine return") for _, chs := range DirCH { returnCount := <-chs fmt.Println("return count=", returnCount) count += returnCount // ReturnFiles := <-chs // if len(ReturnFiles) > 0 { // FindFiles += ReturnFiles + ";" // fmt.Println("list dir chan<-" + ReturnFiles) // } } } //return results fmt.Println("count=", count) ch <- count //FindFiles } func main() { if len(os.Args) < 2 { fmt.Println("please input param of path.") return } fmt.Println(os.Args[1]) path := os.Args[1] //"C:/Users/Administrator/Desktop/publish/test" //path := "c:/QQSave" ch := make(chan int) go listDir(path, ch) fmt.Println("chan<-", <-ch) }