mirror of
https://github.com/crazybber/awesome-patterns.git
synced 2024-11-21 20:36:01 +03:00
select channel with error handling
This commit is contained in:
parent
df6196b7a1
commit
93cce988bb
BIN
concurrency/.DS_Store
vendored
Normal file
BIN
concurrency/.DS_Store
vendored
Normal file
Binary file not shown.
@ -20,6 +20,7 @@ goroutines in some sort of organized fashion.
|
||||
**/
|
||||
|
||||
func main() {
|
||||
resourceLeak()
|
||||
cancellationSignal()
|
||||
}
|
||||
|
||||
|
65
concurrency/select_error_handling/main.go
Normal file
65
concurrency/select_error_handling/main.go
Normal file
@ -0,0 +1,65 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/davecgh/go-spew/spew"
|
||||
)
|
||||
|
||||
func main() {
|
||||
if err := selectWithErrorDemo(); err != nil {
|
||||
spew.Dump(err)
|
||||
}
|
||||
time.Sleep(time.Second * 5)
|
||||
}
|
||||
|
||||
func selectWithErrorDemo() error {
|
||||
// start update race and market
|
||||
count, errChan, doneChan := 2, make(chan error), make(chan bool)
|
||||
|
||||
go func() {
|
||||
// update race
|
||||
if err := doFirstThing(); err != nil {
|
||||
errChan <- err
|
||||
} else {
|
||||
doneChan <- true
|
||||
fmt.Println("Finish First Go Routine")
|
||||
}
|
||||
|
||||
}()
|
||||
|
||||
go func() {
|
||||
// update market
|
||||
if err := doSecondThing(); err != nil {
|
||||
errChan <- err
|
||||
} else {
|
||||
doneChan <- true
|
||||
fmt.Println("Finish Second Go Routine")
|
||||
}
|
||||
}()
|
||||
|
||||
for i := 0; i < count; i++ {
|
||||
select {
|
||||
case err := <-errChan:
|
||||
return err
|
||||
case d := <-doneChan:
|
||||
spew.Dump(i, d)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func doFirstThing() error {
|
||||
time.Sleep(time.Second * 2)
|
||||
fmt.Println("Exectue Do First")
|
||||
return nil
|
||||
|
||||
}
|
||||
|
||||
func doSecondThing() error {
|
||||
time.Sleep(time.Second * 1)
|
||||
fmt.Println("Exectue Do Second")
|
||||
// return errors.New("Error In Second")
|
||||
return nil
|
||||
}
|
Loading…
Reference in New Issue
Block a user