Skip to content

Instantly share code, notes, and snippets.

@nguyentienlong
Last active November 23, 2020 14:08
Show Gist options
  • Save nguyentienlong/cafa823e14af883c45a461ead16ba301 to your computer and use it in GitHub Desktop.
Save nguyentienlong/cafa823e14af883c45a461ead16ba301 to your computer and use it in GitHub Desktop.
why wait group faster than channel?
// 1_wg_example.go
package main
import (
"errors"
"fmt"
"sync"
"time"
)
func doSomething(param string) error {
time.Sleep(2 * time.Second)
if param != "ok" {
return errors.New("an error occurred")
}
return nil
}
func main() {
var wg sync.WaitGroup
params := []string{"ok", "ok", "b", "c", "ok"}
var errors []error
for _, p := range params {
wg.Add(1)
fmt.Printf("p %v\n", p)
go func(p string) {
defer wg.Done()
err := doSomething(p)
if err != nil {
errors = append(errors, err)
}
}(p)
}
wg.Wait()
fmt.Printf("errors %v\n", errors)
}
//2_ch_example.go
package main
import (
"errors"
"fmt"
"time"
)
func doSomething(param string) error {
time.Sleep(2 * time.Second)
if param != "ok" {
return errors.New("an error occurred")
}
return nil
}
func main() {
checkStatus := func(done <-chan interface{}, params ...string) <-chan error {
errors := make(chan error)
go func() {
defer close(errors)
for _, p := range params {
fmt.Printf("p %v\n", p)
err := doSomething(p)
select {
case <-done:
return
case errors <- err:
}
}
}()
return errors
}
done := make(chan interface{})
defer close(done)
params := []string{"ok", "ok", "b", "c", "ok"}
for err := range checkStatus(done, params...) {
fmt.Printf("error %v\n", err)
}
}
3_result.md
➜  compare-cc time go run wg_example.go
p ok
p ok
p b
p c
p ok
errors [an error occurred an error occurred]
go run wg.go  0.23s user 0.20s system 14% cpu 2.933 total
➜  compare-cc time go run ch_example.go
p ok
p ok
error <nil>
error <nil>
p b
p c
error an error occurred
p ok
error an error occurred
error <nil>
go run ch.go  0.26s user 0.23s system 4% cpu 10.579 total
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment