Skip to content

Instantly share code, notes, and snippets.

@paulja
Created March 20, 2018 08:15
Show Gist options
  • Save paulja/34fa45e4972c5a163e77f0ec179752d6 to your computer and use it in GitHub Desktop.
Save paulja/34fa45e4972c5a163e77f0ec179752d6 to your computer and use it in GitHub Desktop.
Advanced synchronisation block with throttling and cancellation in Go by using channels
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)
}
@paulja
Copy link
Author

paulja commented Mar 20, 2018

TODO: Show how to report errors with make(chan error)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment