-
-
Save bcho/7897d36162af0818313e to your computer and use it in GitHub Desktop.
trick
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
// 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