Skip to content

Instantly share code, notes, and snippets.

@slav123
Created July 31, 2022 09:14
Show Gist options
  • Save slav123/ddc836d99a3f20d7069df51ccbfb0039 to your computer and use it in GitHub Desktop.
Save slav123/ddc836d99a3f20d7069df51ccbfb0039 to your computer and use it in GitHub Desktop.
example of using timeout in go with context package
package main
import (
"context"
"fmt"
"time"
)
var globalResult []int
const noOfWorkers = 4
const noOfJobs = 10
func collector(ctx context.Context, results <-chan int, quitCh chan<- bool) {
for {
select {
case j := <-results:
fmt.Printf("result: %d\n", j)
globalResult = append(globalResult, j)
// check if we are done
if len(globalResult) == noOfJobs {
println("full")
quitCh <- true
}
case <-ctx.Done():
println("ctx done")
quitCh <- true
break
}
}
}
func worker(id int, job <-chan int, results chan<- int) {
for j := range job {
fmt.Printf("worker %d started job %d\n", id, j)
time.Sleep(time.Second)
fmt.Printf("worker %d finished job %d\n", id, j)
results <- j
}
}
func main() {
ctx, cancel := context.WithTimeout(context.Background(), time.Second*5)
defer cancel()
jobs := make(chan int, noOfJobs)
results := make(chan int, noOfJobs)
quitCh := make(chan bool, 1)
for w := 1; w <= noOfWorkers; w++ {
go worker(w, jobs, results)
}
go collector(ctx, results, quitCh)
for a := 1; a <= noOfJobs; a++ {
jobs <- a
}
<-quitCh
//close(jobs)
//close(results)
fmt.Printf("globalResult: %v\n", globalResult)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment