Created
February 1, 2017 15:01
-
-
Save briansorahan/d0f2ae977a98b73ea4fb19dce59ed29a to your computer and use it in GitHub Desktop.
Go worker pool. Just toying with ideas.
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
package main | |
import ( | |
"fmt" | |
"math/rand" | |
"time" | |
) | |
type StringsWorker struct { | |
Errors chan<- error | |
Input chan string | |
Output chan string | |
} | |
func (sw StringsWorker) Run() { | |
for s := range sw.Input { | |
switch s { | |
case "foo": | |
time.Sleep(time.Millisecond * time.Duration(rand.Intn(900)+100)) | |
sw.Output <- "bar" | |
case "bar": | |
time.Sleep(time.Millisecond * time.Duration(rand.Intn(900)+100)) | |
sw.Output <- "foo" | |
case "close": | |
sw.Output <- "ok" | |
return | |
} | |
} | |
} | |
type WorkerPool struct { | |
Errors chan error | |
Input chan string | |
Output chan string | |
Workers []StringsWorker | |
} | |
func NewWorkerPool(n int) WorkerPool { | |
pool := WorkerPool{ | |
Errors: make(chan error, 1), | |
Input: make(chan string), | |
Output: make(chan string), | |
Workers: make([]StringsWorker, n), | |
} | |
for i := range pool.Workers { | |
pool.Workers[i] = StringsWorker{ | |
Errors: pool.Errors, | |
Input: make(chan string), | |
Output: make(chan string), | |
} | |
} | |
return pool | |
} | |
func (pool WorkerPool) Run() { | |
for _, worker := range pool.Workers { | |
go worker.Run() | |
} | |
go func() { | |
for s := range pool.Input { | |
} | |
}() | |
} | |
func main() { | |
rand.Seed(time.Now().Unix()) | |
fmt.Println("Hello, playground") | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment