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 @   wangsk  阅读(249)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
点击右上角即可分享
微信分享提示