Skip to content

Instantly share code, notes, and snippets.

@membrive
Created January 20, 2018 09:57
Show Gist options
  • Save membrive/18a613d90810e10806f81e8d9f6966ab to your computer and use it in GitHub Desktop.
Save membrive/18a613d90810e10806f81e8d9f6966ab to your computer and use it in GitHub Desktop.
Goroutines example. Use the time command to verify the elapsed time to finish the execution.
// goroutines errors example
package main
import (
"errors"
"fmt"
"time"
)
func returnError(text string) error {
if text == "error" {
return errors.New("err")
}
return nil
}
func main() {
err1 := make(chan error)
err2 := make(chan error)
// all "go func" run asynchronously
go func() {
// this function needs 10 seconds
time.Sleep(time.Second * 10)
err1 <- returnError("error")
}()
go func() {
// this function needs 5 second
time.Sleep(time.Second * 5)
err2 <- returnError("error")
}()
// synchronous code from here
err := <-err1
if err != nil {
fmt.Println("g1", err)
}
err = <-err2
if err != nil {
fmt.Println("g2", err)
}
close(err1)
close(err2)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment