Created
August 11, 2021 20:26
-
-
Save DanyelMorales/5fd81ca8fb23bbe19709bd2e3d84ac1f to your computer and use it in GitHub Desktop.
OR CHANNELS
This file contains 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" | |
) | |
func main() { | |
var or func(channels ...<-chan interface{}) <-chan interface{} | |
or = func(channels ...<-chan interface{}) <-chan interface{} { | |
switch len(channels) { | |
case 0: | |
return nil | |
case 1: | |
return channels[0] | |
} | |
orDone := make(chan interface{}) | |
go func() { | |
defer close(orDone) | |
switch len(channels) { | |
case 2: | |
select { | |
case <-channels[0]: | |
case <-channels[1]: | |
} | |
default: | |
select { | |
case <-channels[0]: | |
case <-channels[1]: | |
case <-channels[2]: | |
case <-or(append(channels[3:], orDone)...): | |
} | |
} | |
}() | |
return orDone | |
} | |
sig := func(after time.Duration) <-chan interface{} { | |
c := make(chan interface{}) | |
go func() { | |
defer close(c) | |
time.Sleep(after) | |
}() | |
return c | |
} | |
start := time.Now() | |
<-or(sig(5*time.Hour), sig(2*time.Minute), sig(2*time.Second), sig(5*time.Minute)) | |
fmt.Printf("done after %v", time.Since(start)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment