-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfind_file.go
More file actions
81 lines (73 loc) · 1.37 KB
/
find_file.go
File metadata and controls
81 lines (73 loc) · 1.37 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
// Communicating sequential processes
// Don't communicate by sharing memory; share memory by communicating.
package main
import (
"fmt"
"io/ioutil"
"sync"
"time"
)
var query = "git"
var matches int
var workerCount = 0
var maxWorkerCount = 32
var mutex = &sync.Mutex{}
// Bidirection, with block
var searchRequest = make(chan string)
var workerDone = make(chan bool)
var foundResult = make(chan bool)
func main() {
start_t := time.Now()
workerCount = 1
go search("/home/brianlee/", true)
waitWorker()
fmt.Println(matches, "matches")
fmt.Println(time.Since(start_t))
}
func waitWorker() {
for {
select {
case path := <-searchRequest:
mutex.Lock()
workerCount++
mutex.Unlock()
go search(path, true)
case <-foundResult:
matches++
case <-workerDone:
workerCount--
// fmt.Printf("worker left is: %d\n", workerCount)
if workerCount == 0 {
return
}
}
}
}
func search(path string, master bool) {
files, err := ioutil.ReadDir(path)
if err != nil {
if master {
workerDone <- true
}
return
}
for _, file := range files {
name := file.Name()
if name == query {
foundResult <- true
}
if file.IsDir() {
mutex.Lock()
if workerCount < maxWorkerCount {
mutex.Unlock()
searchRequest <- path + name + "/"
} else {
mutex.Unlock()
search(path+name+"/", false)
}
}
}
if master {
workerDone <- true
}
}