// FindAll returns all the Go processes currently running on this host.funcFindAll()[]P{constconcurrencyProcesses=10// limit the maximum number of concurrent reading process taskspss,err:=ps.Processes()iferr!=nil{returnnil}varwgsync.WaitGroupwg.Add(len(pss))found:=make(chanP)limitCh:=make(chanstruct{},concurrencyProcesses)for_,pr:=rangepss{limitCh<-struct{}{}pr:=prgofunc(){deferfunc(){<-limitCh}()deferwg.Done()path,version,agent,ok,err:=isGo(pr)iferr!=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,}}()}gofunc(){wg.Wait()close(found)}()varresults[]Pforp:=rangefound{results=append(results,p)}returnresults}
packagemainimport("fmt""math/rand""sync""time")funcmain(){constconcurrencyProcesses=10// limit the maximum number of concurrent reading process tasksconstjobCount=100varwgsync.WaitGroupwg.Add(jobCount)found:=make(chanint)limitCh:=make(chanstruct{},concurrencyProcesses)fori:=0;i<jobCount;i++{limitCh<-struct{}{}gofunc(valint){deferfunc(){wg.Done()<-limitCh}()waitTime:=rand.Int31n(1000)fmt.Println("job:",val,"wait time:",waitTime,"millisecond")time.Sleep(time.Duration(waitTime)*time.Millisecond)found<-val}(i)}gofunc(){wg.Wait()close(found)}()varresults[]intforp:=rangefound{fmt.Println("Finished job:",p)results=append(results,p)}fmt.Println("result:",results)}
我把 ps.Processes() 的資料,換成 Job 數量來代表,來解釋為什麼麼這段程式碼造成了系統直接 hang 住不動。重點原因在 for 迴圈內的 limitCh <- struct{}{},先看到前面有設定了背景一次只能跑 10 個 Concurrency Processes