go 通过goroutine例程读取文件的行数

package main

import (
	"bufio"
	"fmt"
	"io/fs"
	"os"
	"path/filepath"
	"strings"
	"sync"
)

func FileLine(path string) int {
	file, err := os.Open(path)
	//定义行数
	count := 0
	if err != nil {
		return count
	}

	defer file.Close()
	buffer := bufio.NewReader(file)

	for {
		ctx, _, err := buffer.ReadLine()
		if err != nil {
			return count
		}

		//过滤 1.空行 2.注释
		if strings.TrimSpace(string(ctx)) == "" || strings.HasPrefix(string(ctx), "//") {
			continue
		}

		count++

	}

}

func main() {
	var wg sync.WaitGroup
	//var wg2 sync.WaitGroup
	path := "../."
	//fmt.Println(FileLine(path))
	channel := make(chan int, 10)
	waitChannel := make(chan int)
	total := 0
	//变量文件夹,获取.go文件,统计行数
	filepath.Walk(path, func(path string, info fs.FileInfo, err error) error {
		if !info.IsDir() && filepath.Ext(path) == ".go" {
			wg.Add(1)
			go func() {
				count := FileLine(path)
				channel <- count
				//total += count
				wg.Done()
			}()

		}

		return nil
	})

	//wg2.Add(1)
	go func() {
		for e := range channel {
			total += e
		}
		//wg2.Done()
		waitChannel <- 1
	}()

	wg.Wait()
	close(channel)
	//wg2.Wait()
	<-waitChannel
	fmt.Println(total)
}


posted @ 2022-02-10 15:50  wangsk  阅读(273)  评论(0)    收藏  举报