Created
March 20, 2018 08:15
-
-
Save paulja/34fa45e4972c5a163e77f0ec179752d6 to your computer and use it in GitHub Desktop.
Advanced synchronisation block with throttling and cancellation in Go by using channels
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" | |
"math/rand" | |
"time" | |
) | |
func main() { | |
// first one wins. set of a bunch of tasks and stop when the | |
// first item meets the condition | |
a := 20 // attempts | |
b := make(chan int, 4) // buffer | |
c := make(chan int) // check | |
d := make(chan int) // done | |
rand.Seed(time.Now().UTC().UnixNano()) | |
for i := 0; i < a; i++ { | |
go func(i int) { | |
select { | |
case b <- 0: | |
fmt.Printf("Running: %d\n", i) | |
time.Sleep(2 * time.Second) | |
c <- rand.Intn(8) | |
<-b | |
case <-d: | |
fmt.Printf("Cancelling: %d\n", i) | |
return | |
} | |
}(i) | |
} | |
for i := 0; i < a; i++ { | |
v := <-c | |
fmt.Printf("%d: ", v) | |
if v > 6 { | |
fmt.Printf("match\n") | |
close(d) | |
break | |
} else { | |
fmt.Printf("no match\n") | |
} | |
} | |
fmt.Println("complete") | |
close(b) | |
close(c) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
TODO: Show how to report errors with
make(chan error)