Skip to content

Instantly share code, notes, and snippets.

@maurorappa
Created December 29, 2018 19:44
Show Gist options
  • Save maurorappa/a126c1577f6e28e177d208cfc1bb1b34 to your computer and use it in GitHub Desktop.
Save maurorappa/a126c1577f6e28e177d208cfc1bb1b34 to your computer and use it in GitHub Desktop.
Basic parallel execution in Go
package main
import (
"fmt"
"log"
"os"
//"io/ioutil"
"runtime/pprof"
)
func main() {
// start profiling
f, _ := os.Create("./go.prof")
defer f.Close()
pprof.StartCPUProfile(f)
defer pprof.StopCPUProfile()
//start workers
process0 := make(chan os.FileInfo)
go worker0(process0)
process1 := make(chan os.FileInfo)
go worker1(process1)
process2 := make(chan os.FileInfo)
go worker2(process2)
process3 := make(chan os.FileInfo)
go worker3(process3)
process4 := make(chan os.FileInfo)
go worker4(process4)
// scan /proc
f, err := os.Open("/proc")
if err != nil {
log.Fatal(err)
}
files, err := f.Readdir(-1)
f.Close()
if err != nil {
log.Fatal(err)
}
for x, file := range files {
if x%5 == 0 {
process0 <- file
}
if x%5 == 1 {
process1 <- file
}
if x%5 == 2 {
process2 <- file
}
if x%5 == 3 {
process3 <- file
}
if x%5 == 4 {
process4 <- file
}
}
}
func process(file os.FileInfo) {
cmd := make([]byte, 128)
if file.Mode().IsDir() { // it's a process
pid := file.Name()
f, _ := os.Open("/proc/" + pid + "/cmdline")
n1, _ := f.Read(cmd)
if n1 == 0 {
fmt.Printf("%s kernel process\n", pid)
} else {
fmt.Printf("%s = %s\n", pid, string(cmd))
}
}
}
func worker0(process0 <-chan os.FileInfo) {
for {
file := <-process0
process(file)
}
}
func worker1(process1 <-chan os.FileInfo) {
for {
file := <-process1
process(file)
}
}
func worker2(process2 <-chan os.FileInfo) {
for {
file := <-process2
process(file)
}
}
func worker3(process3 <-chan os.FileInfo) {
for {
file := <-process3
process(file)
}
}
func worker4(process4 <-chan os.FileInfo) {
for {
file := <-process4
process(file)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment