Skip to content

Instantly share code, notes, and snippets.

@thalesfsp
Forked from proudlygeek/commands-channel.go
Created August 18, 2021 17:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thalesfsp/652a81efba91dd70fef4fdedefbdff7b to your computer and use it in GitHub Desktop.
Save thalesfsp/652a81efba91dd70fef4fdedefbdff7b to your computer and use it in GitHub Desktop.
Golang Commands in Goroutines
package main
import (
"fmt"
"log"
"os/exec"
"runtime"
)
type Worker struct {
Command string
Args string
Output chan string
}
func (cmd *Worker) Run() {
out, err := exec.Command(cmd.Command, cmd.Args).Output()
if err != nil {
log.Fatal(err)
}
cmd.Output <- string(out)
}
func Collect(c chan string) {
for {
msg := <-c
fmt.Printf("The command result is %s\n", msg)
}
}
func main() {
runtime.GOMAXPROCS(runtime.NumCPU())
var read string
fmt.Println("When you're ready press ENTER to spawn goroutine")
fmt.Scanln(&read)
c := make(chan string)
phpService := &Worker{Command: "php", Args: "slowService.php", Output: c}
pythonService := &Worker{Command: "python", Args: "mediumService.py", Output: c}
go phpService.Run()
fmt.Println("Doing something...")
go pythonService.Run()
go Collect(c)
fmt.Scanln(&read)
}
import time
time.sleep(1)
print "Python returns!"
<?php
sleep(3);
print "PHP returns!";
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment