Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix the worker concurrency model #126

Merged
merged 1 commit into from
Sep 7, 2020
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
61 changes: 34 additions & 27 deletions goprocess/gp.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,47 +27,54 @@ type P struct {

// FindAll returns all the Go processes currently running on this host.
func FindAll() []P {
const concurrencyProcesses = 10 // limit the maximum number of concurrent reading process tasks
const concurrencyLimit = 10 // max number of concurrent workers
pss, err := ps.Processes()
if err != nil {
return nil
}

input := make(chan ps.Process, len(pss))
output := make(chan P, len(pss))

for _, ps := range pss {
input <- ps
}
close(input)

var wg sync.WaitGroup
wg.Add(len(pss))
found := make(chan P)
limitCh := make(chan struct{}, concurrencyProcesses)
wg.Add(concurrencyLimit) // used to wait for workers to be finished

for _, pr := range pss {
limitCh <- struct{}{}
pr := pr
// Run concurrencyLimit of workers until there
// is no more processes to be checked in the input channel.
for i := 0; i < concurrencyLimit; i++ {
go func() {
defer func() { <-limitCh }()
defer wg.Done()

path, version, agent, ok, err := isGo(pr)
if err != nil {
// TODO(jbd): Return a list of errors.
}
if !ok {
return
}
found <- P{
PID: pr.Pid(),
PPID: pr.PPid(),
Exec: pr.Executable(),
Path: path,
BuildVersion: version,
Agent: agent,
for pr := range input {
path, version, agent, ok, err := isGo(pr)
if err != nil {
// TODO(jbd): Return a list of errors.
continue
}
if !ok {
continue
}
output <- P{
PID: pr.Pid(),
PPID: pr.PPid(),
Exec: pr.Executable(),
Path: path,
BuildVersion: version,
Agent: agent,
}
}
}()
}
go func() {
wg.Wait()
close(found)
}()
wg.Wait() // wait until all workers are finished
close(output) // no more results to be waited for

var results []P
for p := range found {
for p := range output {
results = append(results, p)
}
return results
Expand Down