Last active
June 24, 2022 12:29
-
-
Save ssrlive/5398b121ae29767796472638bb5dcc62 to your computer and use it in GitHub Desktop.
goroutine demo
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"io/ioutil" | |
"time" | |
) | |
var query = "test" | |
var matches int | |
var workerCount = 0 | |
var maxWorkerCount = 32 | |
var searchRequest = make(chan string) | |
var workerDone = make(chan bool) | |
var foundMatch = make(chan bool) | |
func main() { | |
start := time.Now() | |
workerCount = 1 | |
go search("/home/ubuntu/", true) | |
waitForWorkers() | |
fmt.Println(matches, "matches") | |
fmt.Println(time.Since(start)) | |
} | |
func waitForWorkers() { | |
for { | |
select { | |
case path := <-searchRequest: | |
workerCount++ | |
go search(path, true) | |
case <-workerDone: | |
workerCount-- | |
if workerCount == 0 { | |
return | |
} | |
case <-foundMatch: | |
matches++ | |
} | |
} | |
} | |
func search(path string, master bool) { | |
files, err := ioutil.ReadDir(path) | |
if err == nil { | |
for _, file := range files { | |
name := file.Name() | |
if name == query { | |
foundMatch <- true | |
} | |
if file.IsDir() { | |
subPath := path + name + "/" | |
if workerCount < maxWorkerCount { | |
searchRequest <- subPath | |
} else { | |
search(subPath, false) | |
} | |
} | |
} | |
if master { | |
workerDone <- true | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment