码迷,mamicode.com
首页 > 其他好文 > 详细

golang 实现并发计算文件数量

时间:2015-11-21 15:58:24      阅读:188      评论:0      收藏:0      [点我收藏+]

标签:

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])
	fmt.Println("Hello, Go runtine!")
	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)
}

  

golang 实现并发计算文件数量

标签:

原文地址:http://www.cnblogs.com/liughost/p/4983790.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!