I'm using goroutine to traverse all files in the specified directory. I want to know how to limit the number of goroutines under recursive traversal
I wrote this code, but it prompted panic chan send `
package main
import (
"fmt"
"os"
"runtime"
"sync"
"time"
)
var (
wg sync.WaitGroup
// limit = make(chan bool, 20)
// totalchan = make(chan bool)
)
func Work(path string, size int, finished bool) {
fmt.Printf("gn1111: %d\n", runtime.NumGoroutine())
defer func() { wg.Done() }()
fl, err := os.ReadDir(path)
if err == nil {
for _, file := range fl {
if file.IsDir() {
// limit <- true
wg.Add(1)
go Work(path+file.Name()+"/", size, false)
} else {
fmt.Printf("gn2222: %d\n", runtime.NumGoroutine())
}
}
}
// if !finished {
// <-limit
// }
}
func main() {
path := "C:/Windows/"
size := 0
start := time.Now()
wg.Add(1)
go Work(path, size, true)
wg.Wait()
fmt.Printf("total= %d, cost: %v\n", 0, time.Since(start))
}
`