Skip to content

Commit

Permalink
Add example29: handle multiple Go channel
Browse files Browse the repository at this point in the history
Signed-off-by: Bo-Yi Wu <[email protected]>
  • Loading branch information
appleboy committed May 13, 2019
1 parent c612172 commit 68ff6d5
Show file tree
Hide file tree
Showing 3 changed files with 73 additions and 0 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ Learning basic [Golang](https://golang.org/) in one day
* [example25](./example25-traefik-golang-app-lets-encrypt): Running golang app using [traefik & Let's Encrypt & Docker](https://docs.traefik.io/user-guide/docker-and-lets-encrypt/).
* [example27](./example27-how-to-load-env): How to loads environment variables from `.env`.
* [example28](./example28-webserver-with-gracefull-shutdown): Go webserver with gracefull shutdown.
* [example29](./example29-handle-multiple-channel): How to handle multiple Go channel?

[1]:https://github.com/golang/lint
[2]:https://golang.org/cmd/gofmt/
Expand Down
50 changes: 50 additions & 0 deletions example29-handle-multiple-channel/answer/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
package main

import (
"errors"
"fmt"
"math/rand"
"sync"
"time"
)

func main() {
outChan := make(chan int, 100)
errChan := make(chan error)
finishChan := make(chan struct{})
wg := sync.WaitGroup{}
wg.Add(100)
for i := 0; i < 100; i++ {
go func(outChan chan<- int, errChan chan<- error, val int, wg *sync.WaitGroup) {
defer wg.Done()
time.Sleep(time.Duration(rand.Int31n(1000)) * time.Millisecond)
fmt.Println("finished job id:", val)
outChan <- val
if val == 60 {
errChan <- errors.New("error in 60")
}

}(outChan, errChan, i, &wg)
}

go func() {
wg.Wait()
fmt.Println("finish all job")
close(finishChan)
}()

Loop:
for {
select {
case val := <-outChan:
fmt.Println("finished:", val)
case err := <-errChan:
fmt.Println("error:", err)
break Loop
case <-finishChan:
break Loop
case <-time.After(100000 * time.Millisecond):
break Loop
}
}
}
22 changes: 22 additions & 0 deletions example29-handle-multiple-channel/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
package main

import (
"fmt"
"math/rand"
"sync"
"time"
)

func main() {
wg := sync.WaitGroup{}
wg.Add(100)
for i := 0; i < 100; i++ {
go func(val int, wg *sync.WaitGroup) {
time.Sleep(time.Duration(rand.Int31n(1000)) * time.Millisecond)
fmt.Println("finished job id:", val)
wg.Done()
}(i, &wg)
}

wg.Wait()
}

0 comments on commit 68ff6d5

Please sign in to comment.