first commit
This commit is contained in:
@@ -0,0 +1,49 @@
|
||||
package poll
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
// PollJobWorker is a worker that processes jobs from channel.
|
||||
func PollJobWorker(id int, jobs <-chan int, results chan<- string, wg *sync.WaitGroup) {
|
||||
defer wg.Done()
|
||||
for job := range jobs {
|
||||
// simulate processing time
|
||||
time.Sleep(time.Millisecond * 20)
|
||||
res := fmt.Sprintf("worker-%d processed job-%d", id, job)
|
||||
results <- res
|
||||
}
|
||||
}
|
||||
|
||||
// RunPollSimulation launches `workers` workers and sends `jobCount` jobs.
|
||||
func RunPollSimulation(workers, jobCount int) []string {
|
||||
jobs := make(chan int, 10) // capacity 10 as requested
|
||||
results := make(chan string, jobCount)
|
||||
var wg sync.WaitGroup
|
||||
|
||||
// start workers
|
||||
wg.Add(workers)
|
||||
for w := 1; w <= workers; w++ {
|
||||
go PollJobWorker(w, jobs, results, &wg)
|
||||
}
|
||||
|
||||
// send jobs
|
||||
for j := 1; j <= jobCount; j++ {
|
||||
jobs <- j
|
||||
}
|
||||
close(jobs) // close after sending all jobs
|
||||
|
||||
// wait for workers to finish then close results
|
||||
go func() {
|
||||
wg.Wait()
|
||||
close(results)
|
||||
}()
|
||||
|
||||
out := make([]string, 0, jobCount)
|
||||
for r := range results {
|
||||
out = append(out, r)
|
||||
}
|
||||
return out
|
||||
}
|
||||
Reference in New Issue
Block a user