问题
I'm trying make worker pool with looped queue. Is my code idiomatic for Go? And how can I solve concurrent access to *Item
? Pool processing 1 item at time and *Item
don't shared between workers, but sometimes I need change *Item
from main thread. Should I place mutex at every *Item
and when I should lock/unlock it? Or maybe some other structure is possible?
var items = make(map[uint8]*Item)
func worker(queue, done chan uint8) {
for id := range queue {
item := items[id]
// get from http request
n := ...
if item.Count > n {
... // perform some actions with id
}
done<- id
}
}
func dispatcher() {
queue := make(chan uint8, 100)
done := make(chan uint8, 100)
for i := 0; i < 4; i++ {
go worker(queue, done)
}
for id := range jobs {
queue<- id
}
for {
select {
case id := <-done:
queue<- id
...
}
}
}
And main:
func main() {
go dispatcher()
for {
var id, count uint8
fmt.Scan(&id, &count)
// modifying
items[id].Count = count
}
}
P.S. Sorry for my bad English.
来源:https://stackoverflow.com/questions/38817122/go-worker-pool-with-repetitive-queue-structure