-
-
Save jschwinger233/7caf9613cdaf2383ffaa28be7a137944 to your computer and use it in GitHub Desktop.
error selection
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"time" | |
) | |
type e struct{} | |
func chanErr(produceErr bool, d time.Duration, noErrChan chan e) chan e { | |
c := make(chan e) | |
go func() { | |
time.Sleep(d) | |
if !produceErr { | |
noErrChan <- e{} | |
} else { | |
close(c) | |
} | |
}() | |
return c | |
} | |
func println(msg string) { | |
fmt.Printf("[%s] %s\n", | |
time.Now().Format("2006-01-02 15:04:05.999999999"), | |
msg) | |
} | |
func allPassed(checkNum int) (finishChan, noErrChan chan e) { | |
noErrChan = make(chan e, checkNum) | |
finishChan = make(chan e) | |
go func() { | |
for { | |
select { | |
case <-noErrChan: | |
checkNum-- | |
if checkNum == 0 { | |
finishChan <- e{} | |
break | |
} | |
case <-finishChan: | |
break | |
} | |
} | |
}() | |
return | |
} | |
func main() { | |
println("start") | |
var produceErr bool | |
// produceErr = true | |
timeOut := time.NewTimer(time.Second * 2) | |
defer timeOut.Stop() | |
finishChan, noErrChan := allPassed(4) | |
defer close(finishChan) | |
defer close(noErrChan) | |
errA := chanErr(produceErr, time.Second, noErrChan) | |
errB := chanErr(produceErr, time.Second/2, noErrChan) | |
errC := chanErr(true, time.Second/3, noErrChan) | |
errD := chanErr(produceErr, time.Second/4, noErrChan) | |
select { | |
case <-errA: | |
println("got error A") | |
case <-errB: | |
println("got error B") | |
case <-errC: | |
println("got error C") | |
case <-errD: | |
println("got error D") | |
case <-finishChan: | |
println("all passed") | |
case <-timeOut.C: | |
println("time out!") | |
} | |
return | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment