Skip to content

Instantly share code, notes, and snippets.

@bcho
Created July 11, 2015 13:29
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bcho/7897d36162af0818313e to your computer and use it in GitHub Desktop.
Save bcho/7897d36162af0818313e to your computer and use it in GitHub Desktop.
trick
// A cancellable job runner prototype.
package main
import (
"fmt"
"math/rand"
"time"
)
func worker(id int, cancel chan interface{}, done chan int) {
d := rand.Intn(10)
fmt.Printf("%d will take %d secs\n", id, d)
bgWorkChan := func(wait time.Duration) chan interface{} {
c := make(chan interface{})
go func() {
time.Sleep(wait)
c <- nil
}()
return c
}(time.Duration(d) * time.Second)
for {
select {
case <-cancel:
fmt.Printf("%d cancel received\n", id)
fmt.Printf("work should be cancelled\n")
return
case <-bgWorkChan:
fmt.Printf("%d job is finished\n", id)
done <- id
return
}
}
}
func main() {
rand.Seed(time.Now().Unix())
workerCount := 5
c := make(chan interface{}, workerCount)
respChan := make(chan int)
for i := 0; i < workerCount; i++ {
go worker(i, c, respChan)
}
id := <-respChan
fmt.Printf("worker %d has finished, cancel other\n", id)
for i := 0; i < workerCount; i++ {
c <- i
}
time.Sleep(1 * time.Second)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment